-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpreloads.js
More file actions
281 lines (242 loc) · 7.55 KB
/
preloads.js
File metadata and controls
281 lines (242 loc) · 7.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
const { webFrame, ipcRenderer, contextBridge } = require('electron')
const API_NAME = '$$chrome'
const FAKE_API_NAME = `___${API_NAME}`
/*
Injected from apiSpecs.js
*/
const FUNCTION = 'function'
const EVENT = 'event'
const SETTING = 'setting'
const spec = {
tabs: {
create: FUNCTION,
get: FUNCTION,
getCurrent: FUNCTION,
query: FUNCTION,
remove: FUNCTION,
reload: FUNCTION,
// TODO: Replace this with the built in one eventually
executeScript: FUNCTION,
onActivated: EVENT,
onCreated: EVENT,
onUpdated: EVENT,
onRemoved: EVENT
},
windows: {
create: FUNCTION,
get: FUNCTION,
update: FUNCTION,
remove: FUNCTION,
onFocusChanged: EVENT,
onCreated: EVENT,
onUpdated: EVENT,
onRemoved: EVENT
},
debugger: {
attach: FUNCTION,
detach: FUNCTION,
getTargets: FUNCTION,
sendCommand: FUNCTION,
onDetach: EVENT,
onEvent: EVENT
},
browserAction: {
getTitle: FUNCTION,
setTitle: FUNCTION,
setIcon: FUNCTION,
getIcon: FUNCTION,
getPopup: FUNCTION,
setPopup: FUNCTION,
openPopup: FUNCTION,
setBadgeText: FUNCTION,
getBadgeText: FUNCTION,
setBadgeBackgroundColor: FUNCTION,
getBadgeBackgroundColor: FUNCTION,
setBadgeTextColor: FUNCTION,
getBadgeTextColor: FUNCTION,
enable: FUNCTION,
disable: FUNCTION,
isEnabled: FUNCTION,
onClicked: EVENT
},
contextMenus: {
create: FUNCTION,
remove: FUNCTION,
removeAll: FUNCTION,
update: FUNCTION,
onClicked: EVENT
},
webNavigation: {
getFrame: FUNCTION,
getAllFrames: FUNCTION,
onCreatedNavigationTarget: EVENT,
onBeforeNavigate: EVENT,
onCommitted: EVENT,
onDOMContentLoaded: EVENT,
onCompleted: EVENT,
onErrorOccured: EVENT
},
privacy: {
network: {
networkPredictionEnabled: SETTING,
webRTCIPHandlingPolicy: SETTING
},
websites: {
hyperlinkAuditingEnabled: SETTING
}
}
}
function makeEvent (type, name) {
return `extended-webextensions-${type}.${name}`
}
/* Exports get removed when placed into preloads file */
/*
-----------------------------
*/
run()
async function run () {
const isExtensionPage = window.location.href.startsWith('chrome-extension://')
// Running in background page or popup
if (!isExtensionPage) return
const extensionInfo = await getMainWorld()
const rawAPI = {}
let isContextIsolated = true
try {
// TODO: Account for this being invoked more than once?
await contextBridge.exposeInMainWorld(FAKE_API_NAME, '')
} catch {
isContextIsolated = false
}
const toInjectOver = isContextIsolated ? rawAPI : extensionInfo.chrome
injectAPIObject(toInjectOver, 'tabs', null, extensionInfo)
injectAPIObject(toInjectOver, 'windows', null, extensionInfo)
injectAPIObject(toInjectOver, 'debugger', 'debugger', extensionInfo)
injectAPIObject(toInjectOver, 'browserAction', null, extensionInfo)
injectAPIObject(toInjectOver, 'contextMenus', 'contextMenus', extensionInfo)
injectAPIObject(toInjectOver, 'webNavigation', 'webNavigation', extensionInfo)
injectAPIObject(toInjectOver, 'privacy', 'privacy', extensionInfo)
if (isContextIsolated) {
contextBridge.exposeInMainWorld(API_NAME, rawAPI)
}
}
function ensureExists (type, chrome) {
if (!chrome[type]) chrome[type] = {}
}
function hasPermission (permission, manifest) {
if (permission === null) return true
if (!Array.isArray(manifest.permissions)) return false
return manifest.permissions.includes(permission)
}
async function injectAPIObject (rawAPI, type, permission, extensionInfo) {
for (const [name, apiKind] of Object.entries(spec[type])) {
if (typeof apiKind === 'object') {
for (const [subName, subKind] of Object.entries(apiKind)) {
if (subKind === SETTING) {
injectProxy([type, name, subName, 'get'])
injectProxy([type, name, subName, 'set'])
injectProxy([type, name, subName, 'clear'])
}
}
} else if (apiKind === FUNCTION) {
injectFunctionAPI(rawAPI, type, name, permission, extensionInfo)
} else if (apiKind === EVENT) {
injectListenerAPI(rawAPI, type, name, permission, extensionInfo)
} else {
throw new TypeError(`Unknown API Kind: ${apiKind}`)
}
}
}
async function injectListenerAPI (rawAPI, type, name, permission, extensionInfo) {
// Set up listener map for name (rawListener => intermediatelistener
// Set up object for addListener, removeListener, hasListener
const event = makeEvent(type, name)
const listenerMap = new Map()
const { id: extensionId } = extensionInfo
injectProxy([type, name, 'addListener'])
injectProxy([type, name, 'removeListener'])
injectProxy([type, name, 'hasListener'])
ensureExists(type, rawAPI)
if (hasPermission(permission, extensionInfo.manifest)) {
// Wire up listeners
let idCounter = 1
rawAPI[type][name] = {
addListener (listener) {
const listenerId = idCounter++
function handler (e, gotExtensionId, gotListenerId, ...args) {
if (gotExtensionId !== extensionId || gotListenerId !== listenerId) return
listener(...args)
}
listenerMap.set(listener, { listenerId, handler })
ipcRenderer.on(event, handler)
const listenEvent = event + '-add'
ipcRenderer.send(listenEvent, extensionId, listenerId)
},
removeListener (listener) {
if (!listenerMap.has(listener)) return
const { handler, listenerId } = listenerMap.get(listener)
ipcRenderer.removeListener(event, handler)
listenerMap.delete(listener)
const removeEvent = event + '-remove'
ipcRenderer.send(removeEvent, extensionId, listenerId)
},
hasListener (listener) {
return listenerMap.has(listener)
}
}
} else {
// No-op these listeners
rawAPI[type][name] = {
addListener () {
console.error('Attempted to add listener without permission')
},
removeListener () {},
hasListener () {}
}
}
}
async function injectFunctionAPI (rawAPI, type, name, permission, extensionInfo) {
const event = makeEvent(type, name)
const { manifest, id } = extensionInfo
ensureExists(type, rawAPI)
injectProxy([type, name])
if (!hasPermission(permission, manifest)) {
rawAPI[type][name] = async () => {
throw new Error('Permission denied')
}
} else {
rawAPI[type][name] = async (...args) => {
const cb = args.at(-1)
if (typeof cb === 'function') {
const argsNoCB = args.slice(0, -1)
return ipcRenderer.invoke(event, id, ...argsNoCB)
.then(cb, (e) => {
console.error(`Error invoking chrome.${type}.${name}`, e)
rawAPI.runtime.lastError = e
})
} else {
return ipcRenderer.invoke(event, id, ...args)
}
}
}
}
async function getMainWorld () {
const gotChrome = await webFrame.executeJavaScript('window.chrome')
return await extensionInfoFromChrome(gotChrome)
}
async function injectProxy (segments) {
let ensureScript = ''
for (let parentIndex = 0; parentIndex < segments.length - 1; parentIndex++) {
const parentSegments = segments.slice(0, parentIndex + 1).join('.')
ensureScript += `if(!window.chrome.${parentSegments}) window.chrome.${parentSegments} = {}\n`
}
const path = segments.join('.')
await webFrame.executeJavaScript(`
${ensureScript}
window.chrome.${path} = (...args) => ${API_NAME}.${path}(...args)
`)
}
async function extensionInfoFromChrome (chrome) {
const id = chrome.runtime.id
const manifest = await chrome.runtime.getManifest()
return { id, manifest, chrome }
}