-
Notifications
You must be signed in to change notification settings - Fork 15.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: service worker preload scripts #44411
base: main
Are you sure you want to change the base?
Conversation
d13f9c5
to
044dccc
Compare
// Use of this source code is governed by the MIT license that can be | ||
// found in the LICENSE file. | ||
|
||
#include "shell/renderer/preload_utils.h" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice refactoring!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's talk more about evaluateInMainWorld
. Making new functions that allow evaluation of strings directly contravenes web security standards and the original purpose of the context bridge. It will expose a giant security footgun and I'm a strong -1 on exposing such a feature.
I'd love to understand the motivation / usecase and discuss with the Security WG (cc @electron/wg-security) how to solve those use-cases with an API that isn't such a footgun.
@MarshallOfSound the goal with For my particular use case, I'd like to overwrite extension APIs such as const { ipcRenderer, contextBridge } = require('electron');
// Expose setBadgeText API
contextBridge.exposeInMainWorld('electron', {
setBadgeText: (text) => ipcRenderer.send('action.setBadgeText', text)
});
// Overwrite extension API to provide custom functionality
contextBridge.evaluateInMainWorld(`(function () {
chrome.action.setBadgeText = (text) => {
electron.setBadgeText(text);
};
}());`); A potential alternative might be to accept functions. This is similar to what's offered by chrome.scripting APIs. function overrideActionApi () {
chrome.action.setBadgeText = (text) => {
electron.setBadgeText(text);
};
}
contextBridge.evaluateInMainWorld({
func: overrideActionApi,
args: []
}); If this method existing on |
webFrame.executeJavaScript is also a foot gun, it's an API that wouldn't land nowadays and if we could, we'd remove it. I wouldn't use it as an example It sounds like what you want is support for overriding existing APIs from contextBridge which is a thing it supports internally but isn't exposed via API |
@MarshallOfSound The example I provided is limited. However, I do have use cases which require additional logic where providing a complete function would be necessary. For example, some extension APIs require serializing arguments such as action.setIcon. Additionally, the v8::Context provided in this implementation is based on ShadowRealms. These lack most DOM APIs, but could be partially restored by evaluating a method. // Polyfill setTimeout in ShadowRealmGlobalScope
function setTimeoutAsync (delay) {
return contextBridge.evaluateInMainWorld({
func: function mainWorldFunc (delay) {
return new Promise((resolve) => setTimeout(resolve, delay));
},
args: [delay]
});
} |
In this case adding support for zero-copy context bridge transfer of
I don't think this is a good enough usecase to justify a security footgun, the web knows it, chrome knows it, passing strings around to be evalled is just a nightmare. Someones gonna do something silly like |
@MarshallOfSound If I refactor this API to accept a |
Ideally we find a way to avoid this APi surface entirely, does the |
My current constraints:
There's also the issue of future unknowns. JS execution will allow the flexibility to solve varied problems with a small API surface. I'm not sure I fully understand the footgun argument against JS execution (outside of eval strings). Electron provides application developers with full control over a chromium browser environment through JS APIs, and this seems to take away from that level of control. This is a fairly common API provided in projects such as Chrome DevTools Protocol, Chrome Extensions, Puppeteer/Playwright, Selenium, and node's vm module. |
Let me clarify my stance
To give a path forward given the constraints noted above (thanks for those, gives a clear picture of what is needed)
Docs for the function thing could be fun, but at least technically that's the way forward IMO |
5887af5
to
4791bda
Compare
4791bda
to
c6164aa
Compare
I've refactored Tests to guarantee return values go through the context bridge reuse the logic from our webFrame.executeJavaScript world safe test. The internals of chrome.scripting.executeScript internals
contextBridge.evaluateInMainWorld(script) typesThe types are currently using interface EvaluationScript {
/**
* A JavaScript function to evaluate. This function will be serialized which means
* that any bound parameters and execution context will be lost.
*/
func: (...args: any[]) => any;
/**
* The arguments to pass to the provided function. These arguments must be
* JSON-serializable.
*/
args?: any[];
}
interface ContextBridge {
evaluateInMainWorld(evaluationScript: EvaluationScript): any;
} |
|
||
Returns [`ServiceWorkerInfo`](structures/service-worker-info.md) - Information about this service worker | ||
|
||
If the service worker does not exist or is not running this method will throw an exception. | ||
|
||
#### `serviceWorkers.fromVersionID(versionId)` _Experimental_ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
One suggestion from today's review, to make these method names slightly less confusing, make 2 new methods:
getInfoFromVersionID(versionId): ServiceWorkerInfo
getWorkerFromVersionID(versionId): ServiceWorkerMain
Then make serviceWorkers.getFromVersionID
a deprecated alias for getInfoFromVersionID
.
* `evaluationScript` Object | ||
* `func` (...args: any[]) => any - A JavaScript function to evaluate. This function will be serialized which means | ||
that any bound parameters and execution context will be lost. | ||
* `args` any[] (optional) - The arguments to pass to the provided function. These arguments must |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since there was some confusion in the review today about what valid args
values are:
* `args` any[] (optional) - The arguments to pass to the provided function. These arguments must | |
* `args` any[] (optional) - An array of arguments to pass to the provided function. These arguments must |
* `func` (...args: any[]) => any - A JavaScript function to evaluate. This function will be serialized which means | ||
that any bound parameters and execution context will be lost. | ||
* `args` any[] (optional) - The arguments to pass to the provided function. These arguments must | ||
be JSON-serializable. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've been trying to think of a scenario where it'd be backward incompatible to initially implementing this with JSON and then later using contextBridge
to send the values, but unless someone explicitly relied on an argument not JSON serializing well, I think it should be fine to start with JSON serialization and enhance it later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I should be able to give the context-bridged arguments a try so I'll update how that goes soon enough. Since it's an experimental API though, I think it's safe if we have to alter its behavior.
@@ -61,11 +61,17 @@ The `contextBridge` module has the following methods: | |||
* `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]`. | |||
* `api` any - Your API, more information on what this API can be and how it works is available below. | |||
|
|||
### `contextBridge.evaluateInMainWorld(code)` _Experimental_ | |||
### `contextBridge.evaluateInMainWorld(evaluationScript)` _Experimental_ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this be called contextBridge.executeInMainWorld
instead? Using evaluate
in the name makes it seem like we are using eval()
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Initially I was using ShadowRealm.prototype.evaluate as the inspiration for naming.
I'm open to changing this. Especially since it's been revised to accept func/arg params.
Maybe executeScriptInMainWorld?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@samuelmaddock I think that executeScriptInMainWorld
is fine but a bit long but I don't think its a deal breaker either way.
Description of Change
Implements RFC #8
Tip
I recommend reviewing by commit. I've split up the work into logical commits to make reading it more manageable.
Todo
contextBridge.evaluateInMainWorld
to acceptFunction
andArgs[]
rather than astring
feat: service worker preload scripts #44411 (comment)
feat: e pr download-dist <number> build-tools#679
evaluateInMainWorld
should use contextBridge value passing rather than JSON-serialization if possible.registerPreloadScript
shouldn't accept anid
because people will put something random and useless. With future extensions in mind, maybe accept a matcher objectfromVersionID
could be better named to something likegetWorkerFromVersionID
Documentation
ServiceWorkerVersion
andServiceWorkerHost
are relevant for understandingServiceWorkerMain
in this PR.Overview
v8::Context
in renderer worker threads to allow secure interaction with service worker contexts.setPreloads
andgetPreloads
onSession
to support additional targets and more accessible registration from third-party librariesServiceWorkerMain
to main process to enable IPC with renderer worker threads.ServiceWorkerMain
Tracks lifetime of
content::ServiceWorkerVersion
. This class lives as long as a service worker registration is live. A new instance is required for each new 'version' of a service worker script installed.Only
scope
,versionId
, andipc
are currently exposed.Service worker IPCs
ServiceWorkerMain.ipc
matches the implementation ofIpcMain
to enable IPC with the renderer process service worker thread. IPCs sent from the render worker threads are dispatched onSession
; currently only handling service worker IPCs.ipcMainInternal
now handles IPCs from both web frames and service workers. To differentiate the two, an IPC event has atype
of either 'frame' or 'service-worker'.Preload script changes
Preload scripts now require options beyond only their script location. 'frame' and 'service-worker' are now supported via the
type
property. The appropriate scripts will be fetched when our JS bundles are executed in the renderer process.Given the requirements change, I took this opportunity to make our preload APIs better support third-party libraries based on our best practices.
Architecture Flow
As a starting point for reviewing, consider some of the flows this feature implements.
Checklist
npm test
passesRelease Notes
Notes:
registerPreloadScript
,unregisterPreloadScript
,getPreloadScripts
onSession
.getPreloads
andsetPreloads
onSession
.ServiceWorkerMain
class to interact with service workers in the main process.fromVersionID
onServiceWorkers
to get an instance ofServiceWorkerMain
.running-status-changed
event onServiceWorkers
to indicate when a service worker's running status has changed.contextBridge.evaluateInMainWorld
to safely evaluate code across world boundaries.