-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpreloads-raw.js
More file actions
182 lines (157 loc) · 5.7 KB
/
preloads-raw.js
File metadata and controls
182 lines (157 loc) · 5.7 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
const { webFrame, ipcRenderer, contextBridge } = require('electron')
const API_NAME = '$$chrome'
const FAKE_API_NAME = `___${API_NAME}`
/*
Injected from apiSpecs.js
*/
const { FUNCTION, EVENT, SETTING, makeEvent, spec } = require('./apiSpecs')
/*
-----------------------------
*/
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 }
}