From 9c3c441941ad5060ec2db89b805a958a914547f3 Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Sat, 24 Jul 2021 02:23:48 +0200 Subject: Recipe context isolation (#1456) * Enable service contextIsolation * Enable contextIsolation on the service webviews * Expose a new API window.ferdi in the service main world to allow calling back into the service isolated world * Expose a new IPC message inject-js-unsafe from the service isolated world to execute Javascript in the service main world (i.e., run code without context isolation). While the name contains the "unsafe" suffix to show the lack of context isolation, this should mostly be safe, as no nodejs APIs are available in the injected code. * Refactor the Notifications shim into a part in the isolated world that handles displaying and modifying notifications, and a shim in the main world for the Notifications class. The two communicate via the window.ferdi endpoint and a Promise object can be used to detect notification clicks. * Refactor the screen sharing shim into a part in the isolated world that enumerated shareable screens and windows and a shim in the main world that displays the media selector and completes the media selection promise. * Expose the injectJSUnsafe API to recipes to inject javascript code into the main world without context isolation. * Expose setBadge to the main world The window.ferdi.setBadge API can be used to update the service badge from injected unsafe Javascript * Safer script injection into the service main world Make sure that we don't try to serialize stray objects back from the main world to the isolated world by always surrounding the script to be executed by an anonymous function. * Always read recipe assets as utf8 * Remove window.log from recipes We didn't use it anywhere and its behavior was confusing in production mode. * Inject multiple unsafe scripts at the same time * Find in page without remote module Remove the @electron/remote dependency from the find in page (Ctrl+F) functionality. The remote webContents is replaced with Electron IPC. Synchronous IPC messages are handled in the main Electron process, because the renderer process cannot reply to IPC messages synchronously. * Update to latest contextIsolation recipes * Fixing issue with missing 'fs' functions. Co-authored-by: Vijay A --- src/webview/badge.js | 33 ++++++++++ src/webview/find.js | 23 +++++++ src/webview/lib/RecipeWebview.js | 48 +++++++------- src/webview/notifications.js | 88 +++++++++++++++----------- src/webview/recipe.js | 132 ++++++++++++++++++++++----------------- src/webview/screenshare.js | 81 +++++++++++------------- 6 files changed, 239 insertions(+), 166 deletions(-) create mode 100644 src/webview/badge.js create mode 100644 src/webview/find.js (limited to 'src/webview') diff --git a/src/webview/badge.js b/src/webview/badge.js new file mode 100644 index 000000000..1e02fb56a --- /dev/null +++ b/src/webview/badge.js @@ -0,0 +1,33 @@ +const { ipcRenderer } = require('electron'); + +const debug = require('debug')('Ferdi:Plugin:BadgeHandler'); + +export class BadgeHandler { + constructor() { + this.countCache = { + direct: 0, + indirect: 0, + }; + } + + setBadge(direct, indirect) { + if (this.countCache.direct === direct + && this.countCache.indirect === indirect) return; + + // Parse number to integer + // This will correct errors that recipes may introduce, e.g. + // by sending a String instead of an integer + const directInt = parseInt(direct, 10); + const indirectInt = parseInt(indirect, 10); + + const count = { + direct: Math.max(directInt, 0), + indirect: Math.max(indirectInt, 0), + }; + + ipcRenderer.sendToHost('message-counts', count); + Object.assign(this.countCache, count); + + debug('Sending badge count to host', count); + } +} diff --git a/src/webview/find.js b/src/webview/find.js new file mode 100644 index 000000000..040811d68 --- /dev/null +++ b/src/webview/find.js @@ -0,0 +1,23 @@ +import { ipcRenderer } from 'electron'; +import { FindInPage as ElectronFindInPage } from 'electron-find'; + +// Shim to expose webContents functionality to electron-find without @electron/remote +const webContentsShim = { + findInPage: (text, options = {}) => ipcRenderer.sendSync('find-in-page', text, options), + stopFindInPage: (action) => { + ipcRenderer.sendSync('stop-find-in-page', action); + }, + on: (eventName, listener) => { + if (eventName === 'found-in-page') { + ipcRenderer.on('found-in-page', (_, result) => { + listener({ sender: this }, result); + }); + } + }, +}; + +export default class FindInPage extends ElectronFindInPage { + constructor(options = {}) { + super(webContentsShim, options); + } +} diff --git a/src/webview/lib/RecipeWebview.js b/src/webview/lib/RecipeWebview.js index b8fe7dc52..3bb9352f6 100644 --- a/src/webview/lib/RecipeWebview.js +++ b/src/webview/lib/RecipeWebview.js @@ -1,14 +1,12 @@ import { ipcRenderer } from 'electron'; -import { pathExistsSync, readFile } from 'fs-extra'; +import { exists, pathExistsSync, readFile } from 'fs-extra'; const debug = require('debug')('Ferdi:Plugin:RecipeWebview'); class RecipeWebview { - constructor() { - this.countCache = { - direct: 0, - indirect: 0, - }; + constructor(badgeHandler, notificationsHandler) { + this.badgeHandler = badgeHandler; + this.notificationsHandler = notificationsHandler; ipcRenderer.on('poll', () => { this.loopFunc(); @@ -45,24 +43,7 @@ class RecipeWebview { * me directly to me eg. in a channel */ setBadge(direct = 0, indirect = 0) { - if (this.countCache.direct === direct - && this.countCache.indirect === indirect) return; - - // Parse number to integer - // This will correct errors that recipes may introduce, e.g. - // by sending a String instead of an integer - const directInt = parseInt(direct, 10); - const indirectInt = parseInt(indirect, 10); - - const count = { - direct: Math.max(directInt, 0), - indirect: Math.max(indirectInt, 0), - }; - - ipcRenderer.sendToHost('message-counts', count); - Object.assign(this.countCache, count); - - debug('Sending badge count to host', count); + this.badgeHandler.setBadge(direct, indirect); } /** @@ -85,6 +66,23 @@ class RecipeWebview { }); } + injectJSUnsafe(...files) { + Promise.all(files.map(async (file) => { + if (await exists(file)) { + const data = await readFile(file, 'utf8'); + return data; + } + debug('Script not found', file); + return null; + })).then(async (scripts) => { + const scriptsFound = scripts.filter(script => script !== null); + if (scriptsFound.length > 0) { + debug('Inject scripts to main world', scriptsFound); + ipcRenderer.sendToHost('inject-js-unsafe', ...scriptsFound); + } + }); + } + /** * Set a custom handler for turning on and off dark mode * @@ -96,7 +94,7 @@ class RecipeWebview { onNotify(fn) { if (typeof fn === 'function') { - window.Notification.prototype.onNotify = fn; + this.notificationsHandler.onNotify = fn; } } diff --git a/src/webview/notifications.js b/src/webview/notifications.js index 021f05cc3..39a515143 100644 --- a/src/webview/notifications.js +++ b/src/webview/notifications.js @@ -3,49 +3,65 @@ import uuidV1 from 'uuid/v1'; const debug = require('debug')('Ferdi:Notifications'); -class Notification { - static permission = 'granted'; - - constructor(title = '', options = {}) { - debug('New notification', title, options); - this.title = title; - this.options = options; - this.notificationId = uuidV1(); - - ipcRenderer.sendToHost('notification', this.onNotify({ - title: this.title, - options: this.options, - notificationId: this.notificationId, - })); - - ipcRenderer.once(`notification-onclick:${this.notificationId}`, () => { - if (typeof this.onclick === 'function') { - this.onclick(); - } +export class NotificationsHandler { + onNotify = data => data; + + displayNotification(title, options) { + return new Promise((resolve) => { + debug('New notification', title, options); + + const notificationId = uuidV1(); + + ipcRenderer.sendToHost('notification', this.onNotify({ + title, + options, + notificationId, + })); + + ipcRenderer.once(`notification-onclick:${notificationId}`, () => { + resolve(); + }); }); } +} - static requestPermission(cb = null) { - if (!cb) { - return new Promise((resolve) => { - resolve(Notification.permission); - }); - } +export const notificationsClassDefinition = `(() => { + class Notification { + static permission = 'granted'; - if (typeof (cb) === 'function') { - return cb(Notification.permission); + constructor(title = '', options = {}) { + this.title = title; + this.options = options; + window.ferdi.displayNotification(title, options) + .then(() => { + if (typeof (this.onClick) === 'function') { + this.onClick(); + } + }); } - return Notification.permission; - } + static requestPermission(cb = null) { + if (!cb) { + return new Promise((resolve) => { + resolve(Notification.permission); + }); + } - onNotify(data) { - return data; - } + if (typeof (cb) === 'function') { + return cb(Notification.permission); + } - onClick() {} + return Notification.permission; + } - close() {} -} + onNotify(data) { + return data; + } + + onClick() {} + + close() {} + } -window.Notification = Notification; + window.Notification = Notification; +})();`; diff --git a/src/webview/recipe.js b/src/webview/recipe.js index 8da45864b..d143675dc 100644 --- a/src/webview/recipe.js +++ b/src/webview/recipe.js @@ -1,11 +1,9 @@ /* eslint-disable import/first */ -import { ipcRenderer } from 'electron'; -import { getCurrentWebContents } from '@electron/remote'; +import { contextBridge, ipcRenderer } from 'electron'; import path from 'path'; import { autorun, computed, observable } from 'mobx'; import fs from 'fs-extra'; import { debounce } from 'lodash'; -import { FindInPage } from 'electron-find'; // For some services darkreader tries to use the chrome extension message API // This will cause the service to fail loading @@ -23,16 +21,81 @@ import customDarkModeCss from './darkmode/custom'; import RecipeWebview from './lib/RecipeWebview'; import Userscript from './lib/Userscript'; -import { switchDict, getSpellcheckerLocaleByFuzzyIdentifier } from './spellchecker'; -import { injectDarkModeStyle, isDarkModeStyleInjected, removeDarkModeStyle } from './darkmode'; +import { BadgeHandler } from './badge'; import contextMenu from './contextMenu'; -import './notifications'; -import { screenShareCss } from './screenshare'; +import { injectDarkModeStyle, isDarkModeStyleInjected, removeDarkModeStyle } from './darkmode'; +import FindInPage from './find'; +import { NotificationsHandler, notificationsClassDefinition } from './notifications'; +import { getDisplayMediaSelector, screenShareCss, screenShareJs } from './screenshare'; +import { switchDict, getSpellcheckerLocaleByFuzzyIdentifier } from './spellchecker'; -import { DEFAULT_APP_SETTINGS, isDevMode } from '../environment'; +import { DEFAULT_APP_SETTINGS } from '../environment'; const debug = require('debug')('Ferdi:Plugin'); +const badgeHandler = new BadgeHandler(); + +const notificationsHandler = new NotificationsHandler(); + +// Patching window.open +const originalWindowOpen = window.open; + +window.open = (url, frameName, features) => { + debug('window.open', url, frameName, features); + if (!url) { + // The service hasn't yet supplied a URL (as used in Skype). + // Return a new dummy window object and wait for the service to change the properties + const newWindow = { + location: { + href: '', + }, + }; + + const checkInterval = setInterval(() => { + // Has the service changed the URL yet? + if (newWindow.location.href !== '') { + if (features) { + originalWindowOpen(newWindow.location.href, frameName, features); + } else { + // Open the new URL + ipcRenderer.sendToHost('new-window', newWindow.location.href); + } + clearInterval(checkInterval); + } + }, 0); + + setTimeout(() => { + // Stop checking for location changes after 1 second + clearInterval(checkInterval); + }, 1000); + + return newWindow; + } + + // We need to differentiate if the link should be opened in a popup or in the systems default browser + if (!frameName && !features && typeof features !== 'string') { + return ipcRenderer.sendToHost('new-window', url); + } + + if (url) { + return originalWindowOpen(url, frameName, features); + } +}; + +// We can't override APIs here, so we first expose functions via window.ferdi, +// then overwrite the corresponding field of the window object by injected JS. +contextBridge.exposeInMainWorld('ferdi', { + open: window.open, + setBadge: (direct, indirect) => badgeHandler.setBadge(direct || 0, indirect || 0), + displayNotification: (title, options) => notificationsHandler.displayNotification(title, options), + getDisplayMediaSelector, +}); + +ipcRenderer.sendToHost('inject-js-unsafe', + 'window.open = window.ferdi.open;', + notificationsClassDefinition, + screenShareJs); + class RecipeController { @observable settings = { overrideSpellcheckerLanguage: false, @@ -97,7 +160,7 @@ class RecipeController { autorun(() => this.update()); document.addEventListener('DOMContentLoaded', () => { - this.findInPage = new FindInPage(getCurrentWebContents(), { + this.findInPage = new FindInPage({ inputFocusColor: '#CE9FFC', textColor: '#212121', }); @@ -111,7 +174,7 @@ class RecipeController { // Delete module from cache delete require.cache[require.resolve(modulePath)]; try { - this.recipe = new RecipeWebview(); + this.recipe = new RecipeWebview(badgeHandler, notificationsHandler); // eslint-disable-next-line require(modulePath)(this.recipe, {...config, recipe,}); debug('Initialize Recipe', config, recipe); @@ -327,52 +390,3 @@ class RecipeController { /* eslint-disable no-new */ new RecipeController(); /* eslint-enable no-new */ - -// Patching window.open -const originalWindowOpen = window.open; - -window.open = (url, frameName, features) => { - debug('window.open', url, frameName, features); - if (!url) { - // The service hasn't yet supplied a URL (as used in Skype). - // Return a new dummy window object and wait for the service to change the properties - const newWindow = { - location: { - href: '', - }, - }; - - const checkInterval = setInterval(() => { - // Has the service changed the URL yet? - if (newWindow.location.href !== '') { - if (features) { - originalWindowOpen(newWindow.location.href, frameName, features); - } else { - // Open the new URL - ipcRenderer.sendToHost('new-window', newWindow.location.href); - } - clearInterval(checkInterval); - } - }, 0); - - setTimeout(() => { - // Stop checking for location changes after 1 second - clearInterval(checkInterval); - }, 1000); - - return newWindow; - } - - // We need to differentiate if the link should be opened in a popup or in the systems default browser - if (!frameName && !features && typeof features !== 'string') { - return ipcRenderer.sendToHost('new-window', url); - } - - if (url) { - return originalWindowOpen(url, frameName, features); - } -}; - -if (isDevMode) { - window.log = console.log; -} diff --git a/src/webview/screenshare.js b/src/webview/screenshare.js index 84d2e1e95..ab548a625 100644 --- a/src/webview/screenshare.js +++ b/src/webview/screenshare.js @@ -2,6 +2,27 @@ import { desktopCapturer } from 'electron'; const CANCEL_ID = 'desktop-capturer-selection__cancel'; +export async function getDisplayMediaSelector() { + const sources = await desktopCapturer.getSources({ types: ['screen', 'window'] }); + return `
+
    + ${sources.map(({ id, name, thumbnail }) => ` +
  • + +
  • + `).join('')} +
  • + +
  • +
+
`; +} + export const screenShareCss = ` .desktop-capturer-selection { position: fixed; @@ -72,38 +93,12 @@ export const screenShareCss = ` } `; -// Patch getDisplayMedia for screen sharing -window.navigator.mediaDevices.getDisplayMedia = () => async (resolve, reject) => { +export const screenShareJs = ` +window.navigator.mediaDevices.getDisplayMedia = () => new Promise(async (resolve, reject) => { try { - const sources = await desktopCapturer.getSources({ - types: ['screen', 'window'], - }); - const selectionElem = document.createElement('div'); - selectionElem.classList = 'desktop-capturer-selection'; - selectionElem.innerHTML = ` -
-
    - ${sources - .map( - ({ id, name, thumbnail }) => ` -
  • - -
  • - `, - ) - .join('')} -
  • - -
  • -
-
- `; + selectionElem.classList = ['desktop-capturer-selection']; + selectionElem.innerHTML = await window.ferdi.getDisplayMediaSelector(); document.body.appendChild(selectionElem); document @@ -112,25 +107,18 @@ window.navigator.mediaDevices.getDisplayMedia = () => async (resolve, reject) => button.addEventListener('click', async () => { try { const id = button.getAttribute('data-id'); - if (id === CANCEL_ID) { + if (id === '${CANCEL_ID}') { reject(new Error('Cancelled by user')); } else { - const mediaSource = sources.find((source) => source.id === id); - if (!mediaSource) { - throw new Error(`Source with id ${id} does not exist`); - } - - const stream = await window.navigator.mediaDevices.getUserMedia( - { - audio: false, - video: { - mandatory: { - chromeMediaSource: 'desktop', - chromeMediaSourceId: mediaSource.id, - }, + const stream = await window.navigator.mediaDevices.getUserMedia({ + audio: false, + video: { + mandatory: { + chromeMediaSource: 'desktop', + chromeMediaSourceId: id, }, }, - ); + }); resolve(stream); } } catch (err) { @@ -143,4 +131,5 @@ window.navigator.mediaDevices.getDisplayMedia = () => async (resolve, reject) => } catch (err) { reject(err); } -}; +}); +`; -- cgit v1.2.3-70-g09d2