electron/lib/sandboxed_renderer/init.ts

201 lines
7.5 KiB
TypeScript
Raw Normal View History

2020-07-09 04:19:49 +00:00
/* global binding */
2020-05-30 09:56:54 +00:00
import * as events from 'events';
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
2020-05-30 09:56:54 +00:00
import type * as ipcRendererUtilsModule from '@electron/internal/renderer/ipc-renderer-internal-utils';
import type * as ipcRendererInternalModule from '@electron/internal/renderer/ipc-renderer-internal';
import type * as webFrameInitModule from '@electron/internal/renderer/web-frame-init';
import type * as webViewInitModule from '@electron/internal/renderer/web-view/web-view-init';
import type * as windowSetupModule from '@electron/internal/renderer/window-setup';
import type * as securityWarningsModule from '@electron/internal/renderer/security-warnings';
2020-03-20 20:28:31 +00:00
const { EventEmitter } = events;
process._linkedBinding = binding.get;
const v8Util = process._linkedBinding('electron_common_v8_util');
2019-06-02 20:03:03 +00:00
// Expose Buffer shim as a hidden value. This is used by C++ code to
// deserialize Buffer instances sent from browser process.
2020-03-20 20:28:31 +00:00
v8Util.setHiddenValue(global, 'Buffer', Buffer);
2019-06-02 20:03:03 +00:00
// The process object created by webpack is not an event emitter, fix it so
// the API is more compatible with non-sandboxed renderers.
2020-05-30 09:56:54 +00:00
for (const prop of Object.keys(EventEmitter.prototype) as (keyof typeof process)[]) {
if (Object.prototype.hasOwnProperty.call(process, prop)) {
2020-03-20 20:28:31 +00:00
delete process[prop];
}
}
2020-03-20 20:28:31 +00:00
Object.setPrototypeOf(process, EventEmitter.prototype);
const { ipcRendererInternal } = require('@electron/internal/renderer/ipc-renderer-internal') as typeof ipcRendererInternalModule;
const ipcRendererUtils = require('@electron/internal/renderer/ipc-renderer-internal-utils') as typeof ipcRendererUtilsModule;
const { preloadScripts, process: processProps } = ipcRendererUtils.invokeSync(IPC_MESSAGES.BROWSER_SANDBOX_LOAD);
2020-03-20 20:28:31 +00:00
const electron = require('electron');
const loadedModules = new Map<string, any>([
['electron', electron],
['electron/common', electron],
['electron/renderer', electron],
['events', events]
]);
const loadableModules = new Map<string, Function>([
['timers', () => require('timers')],
['url', () => require('url')]
2020-03-20 20:28:31 +00:00
]);
refactor: use mojo for electron internal IPC (#17406) * refactor: use mojo for electron internal IPC * add sender_id, drop MessageSync * remove usages of AtomFrameMsg_Message * iwyu * first draft of renderer->browser direction * refactor to reuse a single ipc interface * implement TakeHeapSnapshot through mojo * the rest of the owl^WtakeHeapSnapshot mojofication * remove no-op overrides in AtomRendererClient * delete renderer-side ElectronApiServiceImpl when its pipe is destroyed * looks like we don't need to overlay the renderer manifest after all * don't try to send 2 replies to a sync rpc * undo changes to manifests.cc * unify sandboxed + unsandboxed ipc events * lint * register ElectronBrowser mojo service on devtools WebContents * fix takeHeapSnapshopt failure paths * {electron_api => atom}::mojom * add send_to_all to ElectronRenderer::Message * keep interface alive until callback is called * review comments * use GetContext from RendererClientBase * robustify a test that uses window.open * MessageSync posts a task to put sync messages in the same queue as async ones * add v8::MicrotasksScope and node::CallbackScope * iwyu * use weakptr to api::WebContents instead of Unretained * make MessageSync an asynchronous message & use non-associated interface * iwyu + comments * remove unused WeakPtrFactory * inline OnRendererMessage[Sync] * cleanups & comments * use helper methods instead of inline lambdas * remove unneeded async in test * add mojo to manifests deps * add gn check for //electron/manifests and mojo * don't register renderer side service until preload has been run * update gn check targets list * move interface registration back to RenderFrameCreated
2019-04-02 22:38:16 +00:00
// ElectronApiServiceImpl will look for the "ipcNative" hidden object when
// invoking the 'onMessage' callback.
v8Util.setHiddenValue(global, 'ipcNative', {
2020-05-30 09:56:54 +00:00
onMessage (internal: boolean, channel: string, ports: MessagePort[], args: any[], senderId: number) {
if (internal && senderId !== 0) {
console.error(`Message ${channel} sent by unexpected WebContents (${senderId})`);
return;
}
2020-03-20 20:28:31 +00:00
const sender = internal ? ipcRendererInternal : electron.ipcRenderer;
sender.emit(channel, { sender, senderId, ports }, ...args);
}
2020-03-20 20:28:31 +00:00
});
// ElectronSandboxedRendererClient will look for the "lifecycle" hidden object when
refactor: use mojo for electron internal IPC (#17406) * refactor: use mojo for electron internal IPC * add sender_id, drop MessageSync * remove usages of AtomFrameMsg_Message * iwyu * first draft of renderer->browser direction * refactor to reuse a single ipc interface * implement TakeHeapSnapshot through mojo * the rest of the owl^WtakeHeapSnapshot mojofication * remove no-op overrides in AtomRendererClient * delete renderer-side ElectronApiServiceImpl when its pipe is destroyed * looks like we don't need to overlay the renderer manifest after all * don't try to send 2 replies to a sync rpc * undo changes to manifests.cc * unify sandboxed + unsandboxed ipc events * lint * register ElectronBrowser mojo service on devtools WebContents * fix takeHeapSnapshopt failure paths * {electron_api => atom}::mojom * add send_to_all to ElectronRenderer::Message * keep interface alive until callback is called * review comments * use GetContext from RendererClientBase * robustify a test that uses window.open * MessageSync posts a task to put sync messages in the same queue as async ones * add v8::MicrotasksScope and node::CallbackScope * iwyu * use weakptr to api::WebContents instead of Unretained * make MessageSync an asynchronous message & use non-associated interface * iwyu + comments * remove unused WeakPtrFactory * inline OnRendererMessage[Sync] * cleanups & comments * use helper methods instead of inline lambdas * remove unneeded async in test * add mojo to manifests deps * add gn check for //electron/manifests and mojo * don't register renderer side service until preload has been run * update gn check targets list * move interface registration back to RenderFrameCreated
2019-04-02 22:38:16 +00:00
v8Util.setHiddenValue(global, 'lifecycle', {
onLoaded () {
2020-05-30 09:56:54 +00:00
(process as events.EventEmitter).emit('loaded');
},
refactor: use mojo for electron internal IPC (#17406) * refactor: use mojo for electron internal IPC * add sender_id, drop MessageSync * remove usages of AtomFrameMsg_Message * iwyu * first draft of renderer->browser direction * refactor to reuse a single ipc interface * implement TakeHeapSnapshot through mojo * the rest of the owl^WtakeHeapSnapshot mojofication * remove no-op overrides in AtomRendererClient * delete renderer-side ElectronApiServiceImpl when its pipe is destroyed * looks like we don't need to overlay the renderer manifest after all * don't try to send 2 replies to a sync rpc * undo changes to manifests.cc * unify sandboxed + unsandboxed ipc events * lint * register ElectronBrowser mojo service on devtools WebContents * fix takeHeapSnapshopt failure paths * {electron_api => atom}::mojom * add send_to_all to ElectronRenderer::Message * keep interface alive until callback is called * review comments * use GetContext from RendererClientBase * robustify a test that uses window.open * MessageSync posts a task to put sync messages in the same queue as async ones * add v8::MicrotasksScope and node::CallbackScope * iwyu * use weakptr to api::WebContents instead of Unretained * make MessageSync an asynchronous message & use non-associated interface * iwyu + comments * remove unused WeakPtrFactory * inline OnRendererMessage[Sync] * cleanups & comments * use helper methods instead of inline lambdas * remove unneeded async in test * add mojo to manifests deps * add gn check for //electron/manifests and mojo * don't register renderer side service until preload has been run * update gn check targets list * move interface registration back to RenderFrameCreated
2019-04-02 22:38:16 +00:00
onExit () {
2020-05-30 09:56:54 +00:00
(process as events.EventEmitter).emit('exit');
refactor: use mojo for electron internal IPC (#17406) * refactor: use mojo for electron internal IPC * add sender_id, drop MessageSync * remove usages of AtomFrameMsg_Message * iwyu * first draft of renderer->browser direction * refactor to reuse a single ipc interface * implement TakeHeapSnapshot through mojo * the rest of the owl^WtakeHeapSnapshot mojofication * remove no-op overrides in AtomRendererClient * delete renderer-side ElectronApiServiceImpl when its pipe is destroyed * looks like we don't need to overlay the renderer manifest after all * don't try to send 2 replies to a sync rpc * undo changes to manifests.cc * unify sandboxed + unsandboxed ipc events * lint * register ElectronBrowser mojo service on devtools WebContents * fix takeHeapSnapshopt failure paths * {electron_api => atom}::mojom * add send_to_all to ElectronRenderer::Message * keep interface alive until callback is called * review comments * use GetContext from RendererClientBase * robustify a test that uses window.open * MessageSync posts a task to put sync messages in the same queue as async ones * add v8::MicrotasksScope and node::CallbackScope * iwyu * use weakptr to api::WebContents instead of Unretained * make MessageSync an asynchronous message & use non-associated interface * iwyu + comments * remove unused WeakPtrFactory * inline OnRendererMessage[Sync] * cleanups & comments * use helper methods instead of inline lambdas * remove unneeded async in test * add mojo to manifests deps * add gn check for //electron/manifests and mojo * don't register renderer side service until preload has been run * update gn check targets list * move interface registration back to RenderFrameCreated
2019-04-02 22:38:16 +00:00
},
onDocumentStart () {
2020-05-30 09:56:54 +00:00
(process as events.EventEmitter).emit('document-start');
refactor: use mojo for electron internal IPC (#17406) * refactor: use mojo for electron internal IPC * add sender_id, drop MessageSync * remove usages of AtomFrameMsg_Message * iwyu * first draft of renderer->browser direction * refactor to reuse a single ipc interface * implement TakeHeapSnapshot through mojo * the rest of the owl^WtakeHeapSnapshot mojofication * remove no-op overrides in AtomRendererClient * delete renderer-side ElectronApiServiceImpl when its pipe is destroyed * looks like we don't need to overlay the renderer manifest after all * don't try to send 2 replies to a sync rpc * undo changes to manifests.cc * unify sandboxed + unsandboxed ipc events * lint * register ElectronBrowser mojo service on devtools WebContents * fix takeHeapSnapshopt failure paths * {electron_api => atom}::mojom * add send_to_all to ElectronRenderer::Message * keep interface alive until callback is called * review comments * use GetContext from RendererClientBase * robustify a test that uses window.open * MessageSync posts a task to put sync messages in the same queue as async ones * add v8::MicrotasksScope and node::CallbackScope * iwyu * use weakptr to api::WebContents instead of Unretained * make MessageSync an asynchronous message & use non-associated interface * iwyu + comments * remove unused WeakPtrFactory * inline OnRendererMessage[Sync] * cleanups & comments * use helper methods instead of inline lambdas * remove unneeded async in test * add mojo to manifests deps * add gn check for //electron/manifests and mojo * don't register renderer side service until preload has been run * update gn check targets list * move interface registration back to RenderFrameCreated
2019-04-02 22:38:16 +00:00
},
onDocumentEnd () {
2020-05-30 09:56:54 +00:00
(process as events.EventEmitter).emit('document-end');
refactor: use mojo for electron internal IPC (#17406) * refactor: use mojo for electron internal IPC * add sender_id, drop MessageSync * remove usages of AtomFrameMsg_Message * iwyu * first draft of renderer->browser direction * refactor to reuse a single ipc interface * implement TakeHeapSnapshot through mojo * the rest of the owl^WtakeHeapSnapshot mojofication * remove no-op overrides in AtomRendererClient * delete renderer-side ElectronApiServiceImpl when its pipe is destroyed * looks like we don't need to overlay the renderer manifest after all * don't try to send 2 replies to a sync rpc * undo changes to manifests.cc * unify sandboxed + unsandboxed ipc events * lint * register ElectronBrowser mojo service on devtools WebContents * fix takeHeapSnapshopt failure paths * {electron_api => atom}::mojom * add send_to_all to ElectronRenderer::Message * keep interface alive until callback is called * review comments * use GetContext from RendererClientBase * robustify a test that uses window.open * MessageSync posts a task to put sync messages in the same queue as async ones * add v8::MicrotasksScope and node::CallbackScope * iwyu * use weakptr to api::WebContents instead of Unretained * make MessageSync an asynchronous message & use non-associated interface * iwyu + comments * remove unused WeakPtrFactory * inline OnRendererMessage[Sync] * cleanups & comments * use helper methods instead of inline lambdas * remove unneeded async in test * add mojo to manifests deps * add gn check for //electron/manifests and mojo * don't register renderer side service until preload has been run * update gn check targets list * move interface registration back to RenderFrameCreated
2019-04-02 22:38:16 +00:00
}
2020-03-20 20:28:31 +00:00
});
const { webFrameInit } = require('@electron/internal/renderer/web-frame-init') as typeof webFrameInitModule;
2020-03-20 20:28:31 +00:00
webFrameInit();
// Pass different process object to the preload script.
2020-05-30 09:56:54 +00:00
const preloadProcess: NodeJS.Process = new EventEmitter() as any;
2020-03-20 20:28:31 +00:00
Object.assign(preloadProcess, binding.process);
Object.assign(preloadProcess, processProps);
2020-03-20 20:28:31 +00:00
Object.assign(process, binding.process);
Object.assign(process, processProps);
process.getProcessMemoryInfo = preloadProcess.getProcessMemoryInfo = () => {
return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO);
};
Object.defineProperty(preloadProcess, 'noDeprecation', {
get () {
2020-03-20 20:28:31 +00:00
return process.noDeprecation;
},
set (value) {
2020-03-20 20:28:31 +00:00
process.noDeprecation = value;
}
2020-03-20 20:28:31 +00:00
});
2020-05-30 09:56:54 +00:00
process.on('loaded', () => (preloadProcess as events.EventEmitter).emit('loaded'));
process.on('exit', () => (preloadProcess as events.EventEmitter).emit('exit'));
(process as events.EventEmitter).on('document-start', () => (preloadProcess as events.EventEmitter).emit('document-start'));
(process as events.EventEmitter).on('document-end', () => (preloadProcess as events.EventEmitter).emit('document-end'));
// This is the `require` function that will be visible to the preload script
2020-05-30 09:56:54 +00:00
function preloadRequire (module: string) {
if (loadedModules.has(module)) {
2020-03-20 20:28:31 +00:00
return loadedModules.get(module);
}
if (loadableModules.has(module)) {
const loadedModule = loadableModules.get(module)!();
loadedModules.set(module, loadedModule);
return loadedModule;
}
2020-03-20 20:28:31 +00:00
throw new Error(`module not found: ${module}`);
}
// Process command line arguments.
const { hasSwitch } = process._linkedBinding('electron_common_command_line');
const { mainFrame } = process._linkedBinding('electron_renderer_web_frame');
// Similar to nodes --expose-internals flag, this exposes _linkedBinding so
// that tests can call it to get access to some test only bindings
if (hasSwitch('unsafely-expose-electron-internals-for-testing')) {
preloadProcess._linkedBinding = process._linkedBinding;
}
const contextIsolation = mainFrame.getWebPreference('contextIsolation');
const webviewTag = mainFrame.getWebPreference('webviewTag');
const isHiddenPage = mainFrame.getWebPreference('hiddenPage');
2020-03-20 20:28:31 +00:00
const usesNativeWindowOpen = true;
const isWebView = mainFrame.getWebPreference('isWebView');
const openerId = mainFrame.getWebPreference('openerId');
switch (window.location.protocol) {
case 'devtools:': {
// Override some inspector APIs.
2020-03-20 20:28:31 +00:00
require('@electron/internal/renderer/inspector');
break;
}
case 'chrome-extension:': {
2020-03-20 20:28:31 +00:00
break;
}
case 'chrome:': {
2020-03-20 20:28:31 +00:00
break;
}
default: {
// Override default web functions.
const { windowSetup } = require('@electron/internal/renderer/window-setup') as typeof windowSetupModule;
windowSetup(isWebView, openerId, isHiddenPage, usesNativeWindowOpen);
}
}
// Load webview tag implementation.
if (process.isMainFrame) {
const { webViewInit } = require('@electron/internal/renderer/web-view/web-view-init') as typeof webViewInitModule;
webViewInit(contextIsolation, webviewTag, isWebView);
}
// Wrap the script into a function executed in global scope. It won't have
// access to the current scope, so we'll expose a few objects as arguments:
//
// - `require`: The `preloadRequire` function
// - `process`: The `preloadProcess` object
2019-06-02 20:03:03 +00:00
// - `Buffer`: Shim of `Buffer` implementation
// - `global`: The window object, which is aliased to `global` by webpack.
2020-05-30 09:56:54 +00:00
function runPreloadScript (preloadSrc: string) {
const preloadWrapperSrc = `(function(require, process, Buffer, global, setImmediate, clearImmediate, exports) {
${preloadSrc}
2020-03-20 20:28:31 +00:00
})`;
// eval in window scope
2020-03-20 20:28:31 +00:00
const preloadFn = binding.createPreloadScript(preloadWrapperSrc);
const { setImmediate, clearImmediate } = require('timers');
2020-03-20 20:28:31 +00:00
preloadFn(preloadRequire, preloadProcess, Buffer, global, setImmediate, clearImmediate, {});
}
for (const { preloadPath, preloadSrc, preloadError } of preloadScripts) {
try {
if (preloadSrc) {
2020-03-20 20:28:31 +00:00
runPreloadScript(preloadSrc);
} else if (preloadError) {
2020-03-20 20:28:31 +00:00
throw preloadError;
}
} catch (error) {
2020-03-20 20:28:31 +00:00
console.error(`Unable to load preload script: ${preloadPath}`);
console.error(error);
ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadPath, error);
}
}
// Warn about security issues
if (process.isMainFrame) {
const { securityWarnings } = require('@electron/internal/renderer/security-warnings') as typeof securityWarningsModule;
2020-03-20 20:28:31 +00:00
securityWarnings();
}