-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathhelper.js
354 lines (291 loc) · 8.71 KB
/
helper.js
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import browser from 'webextension-polyfill';
import { customAlphabet } from 'nanoid/non-secure';
import BrowserAPIService from '@/service/browser-api/BrowserAPIService';
export function escapeElementPolicy(script) {
if (window?.trustedTypes?.createPolicy) {
const escapePolicy = window.trustedTypes.createPolicy('forceInner', {
createHTML: (to_escape) => to_escape,
createScript: (to_escape) => to_escape,
});
return escapePolicy.createScript(script);
}
return script;
}
export function messageSandbox(type, data = {}) {
const nanoid = customAlphabet('1234567890abcdef', 5);
return new Promise((resolve) => {
const messageId = nanoid();
const iframeEl = document.getElementById('sandbox');
iframeEl.contentWindow.postMessage({ id: messageId, type, ...data }, '*');
const messageListener = ({ data: messageData }) => {
if (messageData?.type !== 'sandbox' || messageData?.id !== messageId)
return;
window.removeEventListener('message', messageListener);
resolve(messageData.result);
};
window.addEventListener('message', messageListener);
});
}
export async function getFrames(tabId) {
try {
const frames = await BrowserAPIService.webNavigation.getAllFrames({
tabId,
});
const framesObj = frames.reduce((acc, { frameId, url }) => {
const key = url === 'about:blank' ? '' : url;
acc[key] = frameId;
return acc;
}, {});
return framesObj;
} catch (error) {
console.error(error);
return {};
}
}
export function sendDebugCommand(tabId, method, params = {}) {
return new Promise((resolve) => {
chrome.debugger.sendCommand({ tabId }, method, params, resolve);
});
}
export function attachDebugger(tabId, prevTab) {
return new Promise((resolve) => {
if (prevTab && tabId !== prevTab)
chrome.debugger.detach({ tabId: prevTab });
chrome.debugger.attach({ tabId }, '1.3', () => {
chrome.debugger.sendCommand({ tabId }, 'Page.enable', resolve);
});
});
}
export function waitTabLoaded({ tabId, listenError = false, ms = 10000 }) {
return new Promise((resolve, reject) => {
let timeout = null;
const excludeErrors = ['net::ERR_BLOCKED_BY_CLIENT', 'net::ERR_ABORTED'];
const onErrorOccurred = (details) => {
if (
details.tabId !== tabId ||
details.frameId !== 0 ||
excludeErrors.includes(details.error)
)
return;
clearTimeout(timeout);
BrowserAPIService.webNavigation.onErrorOccurred.removeListener(
onErrorOccurred
);
reject(new Error(details.error));
};
if (ms > 0) {
timeout = setTimeout(() => {
BrowserAPIService.webNavigation.onErrorOccurred.removeListener(
onErrorOccurred
);
reject(new Error('Timeout'));
}, ms);
}
if (listenError && BROWSER_TYPE === 'chrome')
BrowserAPIService.webNavigation.onErrorOccurred.addListener(
onErrorOccurred
);
const activeTabStatus = async () => {
const tab = await BrowserAPIService.tabs.get(tabId);
if (!tab) {
reject(new Error('no-tab'));
return;
}
if (tab.status === 'loading') {
setTimeout(() => {
activeTabStatus();
}, 1000);
return;
}
clearTimeout(timeout);
BrowserAPIService.webNavigation.onErrorOccurred.removeListener(
onErrorOccurred
);
resolve();
};
activeTabStatus();
});
}
export function convertData(data, type) {
if (type === 'any') return data;
let result = data;
switch (type) {
case 'integer':
/* eslint-disable-next-line */
result = typeof data !== 'number' ? +data?.replace(/\D+/g, '') : data;
break;
case 'boolean':
result = Boolean(data);
break;
case 'array':
result = Array.from(data);
break;
case 'string':
result = String(data);
break;
default:
}
return result;
}
export function automaRefDataStr(varName) {
return `
function findData(obj, path) {
const paths = path.split('.');
const isWhitespace = paths.length === 1 && !/\\S/.test(paths[0]);
if (path.startsWith('$last') && Array.isArray(obj)) {
paths[0] = obj.length - 1;
}
if (paths.length === 0 || isWhitespace) return obj;
else if (paths.length === 1) return obj[paths[0]];
let result = obj;
for (let i = 0; i < paths.length; i++) {
if (result[paths[i]] == undefined) {
return undefined;
} else {
result = result[paths[i]];
}
}
return result;
}
function automaRefData(keyword, path = '') {
const data = ${varName}[keyword];
if (!data) return;
return findData(data, path);
}
`;
}
export function injectPreloadScript({ target, scripts, frameSelector }) {
return browser.scripting.executeScript({
target,
world: 'MAIN',
args: [scripts, frameSelector || null],
func: (preloadScripts, frame) => {
let $documentCtx = document;
if (frame) {
const iframeCtx = document.querySelector(frame)?.contentDocument;
if (!iframeCtx) return;
$documentCtx = iframeCtx;
}
preloadScripts.forEach((script) => {
const scriptAttr = `block--${script.id}`;
const isScriptExists = $documentCtx.querySelector(
`.automa-custom-js[${scriptAttr}]`
);
if (isScriptExists) return;
const scriptEl = $documentCtx.createElement('script');
scriptEl.textContent = script.data.code;
scriptEl.setAttribute(scriptAttr, '');
scriptEl.classList.add('automa-custom-js');
$documentCtx.documentElement.appendChild(scriptEl);
});
},
});
}
export async function checkCSPAndInject(
{ target, debugMode, options = {}, injectOptions = {} },
callback
) {
const [isBlockedByCSP] = await browser.scripting.executeScript({
target,
func: () => {
return new Promise((resolve) => {
const escapePolicy = (script) => {
if (window?.trustedTypes?.createPolicy) {
const escapeElPolicy = window.trustedTypes.createPolicy(
'forceInner',
{
createHTML: (to_escape) => to_escape,
createScript: (to_escape) => to_escape,
}
);
return escapeElPolicy.createScript(script);
}
return script;
};
const eventListener = ({ srcElement }) => {
if (!srcElement || srcElement.id !== 'automa-csp') return;
srcElement.remove();
resolve(true);
};
document.addEventListener('securitypolicyviolation', eventListener);
const script = document.createElement('script');
script.id = 'automa-csp';
script.innerText = escapePolicy('console.log("...")');
setTimeout(() => {
document.removeEventListener(
'securitypolicyviolation',
eventListener
);
script.remove();
resolve(false);
}, 500);
document.body.appendChild(script);
});
},
world: 'MAIN',
...(injectOptions || {}),
});
if (isBlockedByCSP.result) {
await new Promise((resolve) => {
chrome.debugger.attach({ tabId: target.tabId }, '1.3', resolve);
});
const jsCode = await callback();
const execResult = await sendDebugCommand(
target.tabId,
'Runtime.evaluate',
{
expression: jsCode,
userGesture: true,
awaitPromise: true,
returnByValue: true,
...(options || {}),
}
);
if (!debugMode) await chrome.debugger.detach({ tabId: target.tabId });
if (!execResult || !execResult.result) {
throw new Error('Unable execute code');
}
if (execResult.result.subtype === 'error') {
throw new Error(execResult.result.description);
}
return {
isBlocked: true,
value: execResult.result.value || null,
};
}
return { isBlocked: false, value: null };
}
function fallbackCopyTextToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.position = 'fixed';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
export function copyTextToClipboard(text) {
return new Promise((resolve, reject) => {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
resolve(true);
return;
}
navigator.clipboard
.writeText(text)
.then(() => {
resolve(true);
})
.catch((error) => {
reject(error);
});
});
}