Skip to content

Commit

Permalink
chore: enable sandbox + disable remote module in default_app
Browse files Browse the repository at this point in the history
  • Loading branch information
miniak committed Mar 10, 2019
1 parent a958eb9 commit f9f009b
Show file tree
Hide file tree
Showing 5 changed files with 96 additions and 53 deletions.
65 changes: 59 additions & 6 deletions default_app/default_app.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { app, BrowserWindow, BrowserWindowConstructorOptions } from 'electron'
import { app, BrowserWindow, shell, ipcMain } from 'electron'
import * as path from 'path'
import * as URL from 'url'

let mainWindow: BrowserWindow | null = null

Expand All @@ -8,18 +9,60 @@ app.on('window-all-closed', () => {
app.quit()
})

export const load = async (appUrl: string) => {
function getElectronPath () {
// Find the shortest path to the electron binary
const absoluteElectronPath = process.execPath
const relativeElectronPath = path.relative(process.cwd(), absoluteElectronPath)
return absoluteElectronPath.length < relativeElectronPath.length
? absoluteElectronPath
: relativeElectronPath
}

function decorateURL (url: string) {
// safely add `?utm_source=default_app
const parsedUrl = URL.parse(url, true)
parsedUrl.query = { ...parsedUrl.query, utm_source: 'default_app' }
return URL.format(parsedUrl)
}

const indexPath = path.resolve(app.getAppPath(), 'index.html')

function isTrustedSender (webContents: Electron.WebContents) {
if (webContents !== (mainWindow && mainWindow.webContents)) {
return false
}

const parsedUrl = URL.parse(webContents.getURL())
return parsedUrl.protocol === 'file:' && parsedUrl.pathname === indexPath
}

ipcMain.on('get-electron-path', (event) => {
try {
event.returnValue = getElectronPath()
} catch {
event.returnValue = null
}
})

ipcMain.on('open-link-externally', (event, url) => {
if (isTrustedSender(event.sender)) {
shell.openExternal(decorateURL(url))
}
})

async function createWindow () {
await app.whenReady()

const options: BrowserWindowConstructorOptions = {
const options: Electron.BrowserWindowConstructorOptions = {
width: 900,
height: 600,
autoHideMenuBar: true,
backgroundColor: '#FFFFFF',
webPreferences: {
contextIsolation: true,
preload: path.resolve(__dirname, 'renderer.js'),
webviewTag: false
contextIsolation: true,
sandbox: true,
enableRemoteModule: false
},
useContentSize: true,
show: false
Expand All @@ -30,9 +73,19 @@ export const load = async (appUrl: string) => {
}

mainWindow = new BrowserWindow(options)

mainWindow.on('ready-to-show', () => mainWindow!.show())

return mainWindow
}

export const loadURL = async (appUrl: string) => {
mainWindow = await createWindow()
mainWindow.loadURL(appUrl)
mainWindow.focus()
}

export const loadFile = async (appPath: string) => {
mainWindow = await createWindow()
mainWindow.loadFile(appPath)
mainWindow.focus()
}
2 changes: 1 addition & 1 deletion default_app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<head>
<title>Electron</title>
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'" />
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'" />
<link href="./styles.css" type="text/css" rel="stylesheet" />
<link href="./octicon/build.css" type="text/css" rel="stylesheet" />
</head>
Expand Down
26 changes: 11 additions & 15 deletions default_app/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,14 @@ function showErrorMessage (message: string) {
process.exit(1)
}

async function loadApplicationByUrl (appUrl: string) {
const { load } = await import('./default_app')
load(appUrl)
async function loadApplicationByURL (appUrl: string) {
const { loadURL } = await import('./default_app')
loadURL(appUrl)
}

async function loadApplicationByFile (appPath: string) {
const { loadFile } = await import('./default_app')
loadFile(appPath)
}

function startRepl () {
Expand All @@ -156,13 +161,9 @@ if (option.file && !option.webdriver) {
const protocol = url.parse(file).protocol
const extension = path.extname(file)
if (protocol === 'http:' || protocol === 'https:' || protocol === 'file:' || protocol === 'chrome:') {
loadApplicationByUrl(file)
loadApplicationByURL(file)
} else if (extension === '.html' || extension === '.htm') {
loadApplicationByUrl(url.format({
protocol: 'file:',
slashes: true,
pathname: path.resolve(file)
}))
loadApplicationByFile(path.resolve(file))
} else {
loadApplicationPackage(file)
}
Expand Down Expand Up @@ -196,10 +197,5 @@ Options:
console.log(welcomeMessage)
}

const indexPath = path.join(__dirname, '/index.html')
loadApplicationByUrl(url.format({
protocol: 'file:',
slashes: true,
pathname: indexPath
}))
loadApplicationByFile('index.html')
}
52 changes: 23 additions & 29 deletions default_app/renderer.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,46 @@
import { remote, shell } from 'electron'
import * as fs from 'fs'
import * as path from 'path'
import * as URL from 'url'
import { ipcRenderer } from 'electron'

function initialize () {
// Find the shortest path to the electron binary
const absoluteElectronPath = remote.process.execPath
const relativeElectronPath = path.relative(process.cwd(), absoluteElectronPath)
const electronPath = absoluteElectronPath.length < relativeElectronPath.length
? absoluteElectronPath
: relativeElectronPath
const electronPath = ipcRenderer.sendSync('get-electron-path')

for (const link of document.querySelectorAll<HTMLLinkElement>('a[href]')) {
// safely add `?utm_source=default_app
const parsedUrl = URL.parse(link.getAttribute('href')!, true)
parsedUrl.query = { ...parsedUrl.query, utm_source: 'default_app' }
const url = URL.format(parsedUrl)

const openLinkExternally = (e: Event) => {
e.preventDefault()
shell.openExternalSync(url)
ipcRenderer.send('open-link-externally', link.getAttribute('href'))
}

link.addEventListener('click', openLinkExternally)
link.addEventListener('auxclick', openLinkExternally)
}

document.querySelector<HTMLAnchorElement>('.electron-version')!.innerText = `Electron v${process.versions.electron}`
document.querySelector<HTMLAnchorElement>('.chrome-version')!.innerText = `Chromium v${process.versions.chrome}`
document.querySelector<HTMLAnchorElement>('.node-version')!.innerText = `Node v${process.versions.node}`
document.querySelector<HTMLAnchorElement>('.v8-version')!.innerText = `v8 v${process.versions.v8}`
document.querySelector<HTMLAnchorElement>('.command-example')!.innerText = `${electronPath} path-to-app`
function replaceText (selector: string, text: string) {
const element = document.querySelector<HTMLElement>(selector)
if (element) {
element.innerText = text
}
}

replaceText('.electron-version', `Electron v${process.versions.electron}`)
replaceText('.chrome-version', `Chromium v${process.versions.chrome}`)
replaceText('.node-version', `Node v${process.versions.node}`)
replaceText('.v8-version', `v8 v${process.versions.v8}`)
replaceText('.command-example', `${electronPath} path-to-app`)

function getOcticonSvg (name: string) {
const octiconPath = path.resolve(__dirname, 'octicon', `${name}.svg`)
if (fs.existsSync(octiconPath)) {
const content = fs.readFileSync(octiconPath, 'utf8')
async function getOcticonSvg (name: string) {
try {
const response = await fetch(`octicon/${name}.svg`)
const div = document.createElement('div')
div.innerHTML = content
div.innerHTML = await response.text()
return div
} catch {
return null
}
return null
}

function loadSVG (element: HTMLSpanElement) {
async function loadSVG (element: HTMLSpanElement) {
for (const cssClass of element.classList) {
if (cssClass.startsWith('octicon-')) {
const icon = getOcticonSvg(cssClass.substr(8))
const icon = await getOcticonSvg(cssClass.substr(8))
if (icon) {
for (const elemClass of element.classList) {
icon.classList.add(elemClass)
Expand Down
4 changes: 2 additions & 2 deletions lib/sandboxed_renderer/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,15 +158,15 @@ const errorUtils = require('@electron/internal/common/error-utils')
// since browserify won't try to include `electron` in the bundle, falling back
// to the `preloadRequire` function above.
function runPreloadScript (preloadSrc) {
const preloadWrapperSrc = `(function(require, process, Buffer, global, setImmediate, clearImmediate) {
const preloadWrapperSrc = `(function(require, process, Buffer, global, setImmediate, clearImmediate, exports) {
${preloadSrc}
})`

// eval in window scope
const preloadFn = binding.createPreloadScript(preloadWrapperSrc)
const { setImmediate, clearImmediate } = require('timers')

preloadFn(preloadRequire, preloadProcess, Buffer, global, setImmediate, clearImmediate)
preloadFn(preloadRequire, preloadProcess, Buffer, global, setImmediate, clearImmediate, {})
}

for (const { preloadPath, preloadSrc, preloadError } of preloadScripts) {
Expand Down

0 comments on commit f9f009b

Please sign in to comment.