guest-window-manager.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. 'use strict'
  2. const {BrowserWindow, ipcMain, webContents} = require('electron')
  3. const {isSameOrigin} = process.atomBinding('v8_util')
  4. const parseFeaturesString = require('../common/parse-features-string')
  5. const hasProp = {}.hasOwnProperty
  6. const frameToGuest = new Map()
  7. // Security options that child windows will always inherit from parent windows
  8. const inheritedWebPreferences = new Map([
  9. ['contextIsolation', true],
  10. ['javascript', false],
  11. ['nativeWindowOpen', true],
  12. ['nodeIntegration', false],
  13. ['sandbox', true],
  14. ['webviewTag', false]
  15. ])
  16. // Copy attribute of |parent| to |child| if it is not defined in |child|.
  17. const mergeOptions = function (child, parent, visited) {
  18. // Check for circular reference.
  19. if (visited == null) visited = new Set()
  20. if (visited.has(parent)) return
  21. visited.add(parent)
  22. for (const key in parent) {
  23. if (!hasProp.call(parent, key)) continue
  24. if (key in child && key !== 'webPreferences') continue
  25. const value = parent[key]
  26. if (typeof value === 'object') {
  27. child[key] = mergeOptions(child[key] || {}, value, visited)
  28. } else {
  29. child[key] = value
  30. }
  31. }
  32. visited.delete(parent)
  33. return child
  34. }
  35. // Merge |options| with the |embedder|'s window's options.
  36. const mergeBrowserWindowOptions = function (embedder, options) {
  37. if (options.webPreferences == null) {
  38. options.webPreferences = {}
  39. }
  40. if (embedder.browserWindowOptions != null) {
  41. // Inherit the original options if it is a BrowserWindow.
  42. mergeOptions(options, embedder.browserWindowOptions)
  43. } else {
  44. // Or only inherit webPreferences if it is a webview.
  45. mergeOptions(options.webPreferences, embedder.getLastWebPreferences())
  46. }
  47. // Inherit certain option values from parent window
  48. for (const [name, value] of inheritedWebPreferences) {
  49. if (embedder.getLastWebPreferences()[name] === value) {
  50. options.webPreferences[name] = value
  51. }
  52. }
  53. // Sets correct openerId here to give correct options to 'new-window' event handler
  54. options.webPreferences.openerId = embedder.id
  55. return options
  56. }
  57. // Setup a new guest with |embedder|
  58. const setupGuest = function (embedder, frameName, guest, options) {
  59. // When |embedder| is destroyed we should also destroy attached guest, and if
  60. // guest is closed by user then we should prevent |embedder| from double
  61. // closing guest.
  62. const guestId = guest.webContents.id
  63. const closedByEmbedder = function () {
  64. guest.removeListener('closed', closedByUser)
  65. guest.destroy()
  66. }
  67. const closedByUser = function () {
  68. embedder.send('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_' + guestId)
  69. embedder.removeListener('render-view-deleted', closedByEmbedder)
  70. }
  71. embedder.once('render-view-deleted', closedByEmbedder)
  72. guest.once('closed', closedByUser)
  73. if (frameName) {
  74. frameToGuest.set(frameName, guest)
  75. guest.frameName = frameName
  76. guest.once('closed', function () {
  77. frameToGuest.delete(frameName)
  78. })
  79. }
  80. return guestId
  81. }
  82. // Create a new guest created by |embedder| with |options|.
  83. const createGuest = function (embedder, url, frameName, options, postData) {
  84. let guest = frameToGuest.get(frameName)
  85. if (frameName && (guest != null)) {
  86. guest.loadURL(url)
  87. return guest.webContents.id
  88. }
  89. // Remember the embedder window's id.
  90. if (options.webPreferences == null) {
  91. options.webPreferences = {}
  92. }
  93. guest = new BrowserWindow(options)
  94. if (!options.webContents || url !== 'about:blank') {
  95. // We should not call `loadURL` if the window was constructed from an
  96. // existing webContents(window.open in a sandboxed renderer) and if the url
  97. // is not 'about:blank'.
  98. //
  99. // Navigating to the url when creating the window from an existing
  100. // webContents would not be necessary(it will navigate there anyway), but
  101. // apparently there's a bug that allows the child window to be scripted by
  102. // the opener, even when the child window is from another origin.
  103. //
  104. // That's why the second condition(url !== "about:blank") is required: to
  105. // force `OverrideSiteInstanceForNavigation` to be called and consequently
  106. // spawn a new renderer if the new window is targeting a different origin.
  107. //
  108. // If the URL is "about:blank", then it is very likely that the opener just
  109. // wants to synchronously script the popup, for example:
  110. //
  111. // let popup = window.open()
  112. // popup.document.body.write('<h1>hello</h1>')
  113. //
  114. // The above code would not work if a navigation to "about:blank" is done
  115. // here, since the window would be cleared of all changes in the next tick.
  116. const loadOptions = {}
  117. if (postData != null) {
  118. loadOptions.postData = postData
  119. loadOptions.extraHeaders = 'content-type: application/x-www-form-urlencoded'
  120. if (postData.length > 0) {
  121. const postDataFront = postData[0].bytes.toString()
  122. const boundary = /^--.*[^-\r\n]/.exec(postDataFront)
  123. if (boundary != null) {
  124. loadOptions.extraHeaders = `content-type: multipart/form-data; boundary=${boundary[0].substr(2)}`
  125. }
  126. }
  127. }
  128. guest.loadURL(url, loadOptions)
  129. }
  130. return setupGuest(embedder, frameName, guest, options)
  131. }
  132. const getGuestWindow = function (guestContents) {
  133. let guestWindow = BrowserWindow.fromWebContents(guestContents)
  134. if (guestWindow == null) {
  135. const hostContents = guestContents.hostWebContents
  136. if (hostContents != null) {
  137. guestWindow = BrowserWindow.fromWebContents(hostContents)
  138. }
  139. }
  140. return guestWindow
  141. }
  142. // Checks whether |sender| can access the |target|:
  143. // 1. Check whether |sender| is the parent of |target|.
  144. // 2. Check whether |sender| has node integration, if so it is allowed to
  145. // do anything it wants.
  146. // 3. Check whether the origins match.
  147. //
  148. // However it allows a child window without node integration but with same
  149. // origin to do anything it wants, when its opener window has node integration.
  150. // The W3C does not have anything on this, but from my understanding of the
  151. // security model of |window.opener|, this should be fine.
  152. const canAccessWindow = function (sender, target) {
  153. return (target.getLastWebPreferences().openerId === sender.id) ||
  154. (sender.getLastWebPreferences().nodeIntegration === true) ||
  155. isSameOrigin(sender.getURL(), target.getURL())
  156. }
  157. // Routed window.open messages with raw options
  158. ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', (event, url, frameName, features) => {
  159. if (url == null || url === '') url = 'about:blank'
  160. if (frameName == null) frameName = ''
  161. if (features == null) features = ''
  162. const options = {}
  163. const ints = ['x', 'y', 'width', 'height', 'minWidth', 'maxWidth', 'minHeight', 'maxHeight', 'zoomFactor']
  164. const webPreferences = ['zoomFactor', 'nodeIntegration', 'preload', 'javascript', 'contextIsolation', 'webviewTag']
  165. const disposition = 'new-window'
  166. // Used to store additional features
  167. const additionalFeatures = []
  168. // Parse the features
  169. parseFeaturesString(features, function (key, value) {
  170. if (value === undefined) {
  171. additionalFeatures.push(key)
  172. } else {
  173. // Don't allow webPreferences to be set since it must be an object
  174. // that cannot be directly overridden
  175. if (key === 'webPreferences') return
  176. if (webPreferences.includes(key)) {
  177. if (options.webPreferences == null) {
  178. options.webPreferences = {}
  179. }
  180. options.webPreferences[key] = value
  181. } else {
  182. options[key] = value
  183. }
  184. }
  185. })
  186. if (options.left) {
  187. if (options.x == null) {
  188. options.x = options.left
  189. }
  190. }
  191. if (options.top) {
  192. if (options.y == null) {
  193. options.y = options.top
  194. }
  195. }
  196. if (options.title == null) {
  197. options.title = frameName
  198. }
  199. if (options.width == null) {
  200. options.width = 800
  201. }
  202. if (options.height == null) {
  203. options.height = 600
  204. }
  205. for (const name of ints) {
  206. if (options[name] != null) {
  207. options[name] = parseInt(options[name], 10)
  208. }
  209. }
  210. ipcMain.emit('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN', event,
  211. url, frameName, disposition, options, additionalFeatures)
  212. })
  213. // Routed window.open messages with fully parsed options
  214. ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_INTERNAL_WINDOW_OPEN', function (event, url, frameName,
  215. disposition, options,
  216. additionalFeatures, postData) {
  217. options = mergeBrowserWindowOptions(event.sender, options)
  218. event.sender.emit('new-window', event, url, frameName, disposition, options, additionalFeatures)
  219. const {newGuest} = event
  220. if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) {
  221. if (newGuest != null) {
  222. if (options.webContents === newGuest.webContents) {
  223. // the webContents is not changed, so set defaultPrevented to false to
  224. // stop the callers of this event from destroying the webContents.
  225. event.defaultPrevented = false
  226. }
  227. event.returnValue = setupGuest(event.sender, frameName, newGuest, options)
  228. } else {
  229. event.returnValue = null
  230. }
  231. } else {
  232. event.returnValue = createGuest(event.sender, url, frameName, options, postData)
  233. }
  234. })
  235. ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', function (event, guestId) {
  236. const guestContents = webContents.fromId(guestId)
  237. if (guestContents == null) return
  238. if (!canAccessWindow(event.sender, guestContents)) {
  239. console.error(`Blocked ${event.sender.getURL()} from closing its opener.`)
  240. return
  241. }
  242. const guestWindow = getGuestWindow(guestContents)
  243. if (guestWindow != null) guestWindow.destroy()
  244. })
  245. ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_METHOD', function (event, guestId, method, ...args) {
  246. const guestContents = webContents.fromId(guestId)
  247. if (guestContents == null) {
  248. event.returnValue = null
  249. return
  250. }
  251. if (!canAccessWindow(event.sender, guestContents)) {
  252. console.error(`Blocked ${event.sender.getURL()} from calling ${method} on its opener.`)
  253. event.returnValue = null
  254. return
  255. }
  256. const guestWindow = getGuestWindow(guestContents)
  257. if (guestWindow != null) {
  258. event.returnValue = guestWindow[method](...args)
  259. } else {
  260. event.returnValue = null
  261. }
  262. })
  263. ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', function (event, guestId, message, targetOrigin, sourceOrigin) {
  264. if (targetOrigin == null) {
  265. targetOrigin = '*'
  266. }
  267. const guestContents = webContents.fromId(guestId)
  268. if (guestContents == null) return
  269. // The W3C does not seem to have word on how postMessage should work when the
  270. // origins do not match, so we do not do |canAccessWindow| check here since
  271. // postMessage across origins is useful and not harmful.
  272. if (targetOrigin === '*' || isSameOrigin(guestContents.getURL(), targetOrigin)) {
  273. const sourceId = event.sender.id
  274. guestContents.send('ELECTRON_GUEST_WINDOW_POSTMESSAGE', sourceId, message, sourceOrigin)
  275. }
  276. })
  277. ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', function (event, guestId, method, ...args) {
  278. const guestContents = webContents.fromId(guestId)
  279. if (guestContents == null) return
  280. if (canAccessWindow(event.sender, guestContents)) {
  281. guestContents[method](...args)
  282. } else {
  283. console.error(`Blocked ${event.sender.getURL()} from calling ${method} on its opener.`)
  284. }
  285. })
  286. ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD_SYNC', function (event, guestId, method, ...args) {
  287. const guestContents = webContents.fromId(guestId)
  288. if (guestContents == null) {
  289. event.returnValue = null
  290. return
  291. }
  292. if (canAccessWindow(event.sender, guestContents)) {
  293. event.returnValue = guestContents[method](...args)
  294. } else {
  295. console.error(`Blocked ${event.sender.getURL()} from calling ${method} on its opener.`)
  296. event.returnValue = null
  297. }
  298. })