Repository navigation
Expand file tree
/
Copy pathcommon.js
More file actions
388 lines (346 loc) · 13.7 KB
/
Copy pathcommon.js
File metadata and controls
388 lines (346 loc) · 13.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
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// Shared code for background script, popup and options (Firefox + Chrome, Manifest V3).
// Firefox exposes `browser`, Chrome exposes `chrome` (both return promises in MV3).
const api = globalThis.browser || globalThis.chrome;
const LOG_PREFIX = '[XDEBUG_PROFILE]';
// --- Safe access to WebExtension APIs ---
// Browsers support different sets of APIs (e.g. Firefox for Android has no windows and commands),
// so every API method and event is checked before use.
// Returns the API object or function by path ('tabs.getCurrent'), undefined if the browser has none
function getApi(path) {
let node = api;
for (let part of path.split('.')) {
if (node === undefined || node === null) {
return undefined;
}
node = node[part];
}
return node;
}
function hasApi(path) {
return getApi(path) !== undefined;
}
// Calls an API method if the browser has it, otherwise returns fallback.
// The result is returned as is (usually a promise), so callers can await it in both cases.
function callApi(path, args, fallback) {
let method = getApi(path);
if (typeof method !== 'function') {
log('API is not available:', path);
return fallback;
}
return method.apply(getApi(path.split('.').slice(0, -1).join('.')), args || []);
}
// The same for APIs the action can't work without: throws an error that is shown to the user
function requireApi(path, args) {
let method = getApi(path);
if (typeof method !== 'function') {
throw new Error('API is not available in this browser: ' + path);
}
return method.apply(getApi(path.split('.').slice(0, -1).join('.')), args || []);
}
// Subscribes to an API event if the browser has it, returns false otherwise
function addApiListener(path, listener) {
let event = getApi(path);
if (!event || typeof event.addListener !== 'function') {
log('API event is not available:', path);
return false;
}
event.addListener(listener);
return true;
}
// firstPartyDomain exists only in Firefox, Chrome rejects unknown properties
const IS_FIREFOX = hasApi('runtime.getBrowserInfo');
// Settings are kept in storage.sync, or in storage.local if the browser has no sync storage
const SETTINGS_AREA = hasApi('storage.sync') ? 'sync' : 'local';
// Supported Xdebug triggers. Storage keys of PROFILE are the same as in old versions.
const TRIGGERS = [
// XDEBUG_SESSION value is passed to the IDE as IDE key (matters only for DBGp proxy or picky IDEs)
{ id: 'debug', label: 'Debug', badge: 'D', key: 'cookie_XDEBUG_SESSION', defaultName: 'XDEBUG_SESSION', defaultValue: 'vsc', ide: true },
{ id: 'profile', label: 'Profile', badge: 'P', key: 'cookie_XDEBUG_PROFILE', defaultName: 'XDEBUG_PROFILE', defaultValue: 'Y' },
{ id: 'trace', label: 'Trace', badge: 'T', key: 'cookie_XDEBUG_TRACE', defaultName: 'XDEBUG_TRACE', defaultValue: 'Y' }
];
const DEFAULT_ON_COLOR = 'red';
const DEFAULT_OFF_COLOR = 'light';
// Must match host_permissions in manifest.json
const SITE_ORIGINS = { origins: ['http://*/*', 'https://*/*'] };
// Default IDE keys: VS Code - php.debug.ideKey of xdebug/vscode-php-debug,
// others - as in Xdebug helper extension. Any other value is a custom key.
const IDE_PRESETS = [
{ label: 'VS Code', key: 'vsc' },
{ label: 'PhpStorm', key: 'PHPSTORM' },
{ label: 'NetBeans', key: 'netbeans-xdebug' },
{ label: 'Eclipse', key: 'XDEBUG_ECLIPSE' },
{ label: 'MacGDBp', key: 'macgdbp' }
];
// Set when the user has chosen the IDE on the options page (welcome block is shown until then)
const IDE_CHOSEN_KEY = 'ide_chosen';
// Localized string from _locales/*/messages.json, falls back to the key itself
function t(key, ...substitutions) {
let message = callApi('i18n.getMessage', [key, substitutions.map(String)], '');
if (!message) {
console.warn(LOG_PREFIX, 'i18n: no message for', key);
return key;
}
return message;
}
// Translates elements with data-i18n (text), data-i18n-placeholder and data-i18n-title attributes
function localizePage(root) {
if (!root) {
root = document;
// Language of the translation actually used (stored in messages.json)
document.documentElement.lang = t('langCode');
}
root.querySelectorAll('[data-i18n]').forEach(el => { el.textContent = t(el.dataset.i18n); });
root.querySelectorAll('[data-i18n-placeholder]').forEach(el => { el.placeholder = t(el.dataset.i18nPlaceholder); });
root.querySelectorAll('[data-i18n-title]').forEach(el => { el.title = t(el.dataset.i18nTitle); });
}
// RFC 6265: cookie-name is a token, cookie-value has no spaces, quotes, commas, semicolons, backslashes
function isValidCookieName(name) {
return /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name);
}
function isValidCookieValue(value) {
return /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/.test(value);
}
function getIdePreset(key) {
return IDE_PRESETS.find(preset => preset.key === key) || null;
}
// "VS Code (vsc)" or "custom key (VSCODE)"
function getIdeLabel(key) {
let preset = getIdePreset(key);
return (preset ? preset.label : t('customKey')) + ' (' + key + ')';
}
function log(...args) {
console.debug(LOG_PREFIX, ...args);
}
function logError(...args) {
console.error(LOG_PREFIX, ...args);
}
// Cookies can be managed only for regular web pages (not about:, chrome:, file:, moz-extension: etc.)
function isSupportedUrl(url) {
return /^https?:\/\//i.test(url || '');
}
async function hasHostPermission() {
try {
// Without the permissions API host permissions are granted at install time
return await callApi('permissions.contains', [SITE_ORIGINS], true);
} catch (e) {
logError('permissions.contains failed', e);
return false;
}
}
// Must be called from a user action handler (click)
async function requestHostPermission() {
let granted = await requireApi('permissions.request', [SITE_ORIGINS]);
log('host permission granted:', granted);
return granted;
}
// Returns [{...trigger, name, value, siteValue}] with values from settings.
// host - apply per-site overrides (IDE key of the debug trigger), siteValue is true then.
async function getTriggerSettings(host) {
let keys = [];
for (let trigger of TRIGGERS) {
keys.push(trigger.key, trigger.key + '_value');
}
let config = await callApi('storage.' + SETTINGS_AREA + '.get', [keys], {});
let siteIdeKey = host ? await getSiteIdeKey(host) : '';
return TRIGGERS.map(trigger => Object.assign({}, trigger, {
label: t('trigger_' + trigger.id),
name: config[trigger.key] || trigger.defaultName,
value: (trigger.ide && siteIdeKey) || config[trigger.key + '_value'] || trigger.defaultValue,
siteValue: !!(trigger.ide && siteIdeKey)
}));
}
// IDE key for a site, overrides the global one ('' - use global).
// Useful when some projects work through DBGp proxy with their own key.
async function getSiteIdeKey(host) {
let key = 'idekey:' + host;
let data = await callApi('storage.local.get', [key], {});
return data[key] || '';
}
async function setSiteIdeKey(host, ideKey) {
let key = 'idekey:' + host;
if (ideKey) {
await callApi('storage.local.set', [{ [key]: ideKey }]);
} else {
await callApi('storage.local.remove', [key]);
}
log('IDE key for', host, '=', ideKey || '(global)');
}
async function getColors() {
let config = await callApi('storage.' + SETTINGS_AREA + '.get', [['cookie_XDEBUG_PROFILE_on_color', 'cookie_XDEBUG_PROFILE_off_color']], {});
return {
on: config.cookie_XDEBUG_PROFILE_on_color || DEFAULT_ON_COLOR,
off: config.cookie_XDEBUG_PROFILE_off_color || DEFAULT_OFF_COLOR
};
}
// Firefox: tab.cookieStoreId (containers, private windows).
// Chrome: no cookieStoreId in tabs, find the store that contains the tab ("0" - normal, "1" - incognito).
async function getStoreId(tab) {
if (tab.cookieStoreId) {
return tab.cookieStoreId;
}
let stores = await callApi('cookies.getAllCookieStores', [], []);
for (let store of stores) {
if (store.tabIds && store.tabIds.includes(tab.id)) {
return store.id;
}
}
log('getStoreId: store not found for tab', tab.id, 'using default');
return undefined;
}
function getHost(url) {
try {
return new URL(url).hostname;
} catch (e) {
return '';
}
}
// Domains the cookie can be set for: the host itself and its parent domains (at least 2 labels).
// Public suffixes (like co.uk) are rejected by the browser itself, the error is shown in popup.
function getDomainCandidates(host) {
if (!host || host.indexOf('.') === -1 || /^[\d.]+$/.test(host) || host.indexOf(':') !== -1 || host.startsWith('[')) {
return [];
}
let labels = host.split('.');
let result = [];
for (let i = 0; i <= labels.length - 2; i++) {
result.push(labels.slice(i).join('.'));
}
return result;
}
// Scope is remembered per host: '' - host-only cookie, 'example.com' - cookie for .example.com and subdomains
async function getScope(host) {
let key = 'scope:' + host;
let data = await callApi('storage.local.get', [key], {});
let scope = data[key] || '';
if (scope && !getDomainCandidates(host).includes(scope)) {
return '';
}
return scope;
}
async function setScope(host, scope) {
let key = 'scope:' + host;
if (scope) {
await callApi('storage.local.set', [{ [key]: scope }]);
} else {
await callApi('storage.local.remove', [key]);
}
log('scope for', host, '=', scope || '(host only)');
}
async function getCookie(tab, trigger) {
if (!tab || !isSupportedUrl(tab.url)) {
return null;
}
let cookie = null;
try {
cookie = await requireApi('cookies.get', [{
url: tab.url,
name: trigger.name,
storeId: await getStoreId(tab)
}]);
} catch (e) {
logError('getCookie failed for', tab.url, trigger.name, e);
return null;
}
if (cookie && cookie.value == trigger.value) {
return cookie;
}
if (cookie) {
log('getCookie: cookie', trigger.name, 'has unexpected value', cookie.value, 'expected', trigger.value);
}
return null;
}
// Returns {debug: cookie|null, profile: ..., trace: ...}
async function getStates(tab) {
let triggers = await getTriggerSettings(getHost(tab.url));
let states = {};
for (let trigger of triggers) {
states[trigger.id] = await getCookie(tab, trigger);
}
return states;
}
function cookieUrl(cookie) {
return (cookie.secure ? 'https://' : 'http://') + cookie.domain.replace(/^\./, '') + cookie.path;
}
async function removeCookie(cookie) {
let details = {
url: cookieUrl(cookie),
name: cookie.name,
storeId: cookie.storeId
};
if (IS_FIREFOX && cookie.firstPartyDomain !== undefined) {
details.firstPartyDomain = cookie.firstPartyDomain;
}
await requireApi('cookies.remove', [details]);
log('removed', cookie.name, 'for', details.url, 'store', cookie.storeId);
}
// Removes all cookies with this name that are sent to the tab url (host-only and domain ones)
async function disableTrigger(tab, trigger) {
let query = {
url: tab.url,
name: trigger.name,
storeId: await getStoreId(tab)
};
if (IS_FIREFOX) {
query.firstPartyDomain = null;
}
let cookies = await requireApi('cookies.getAll', [query]);
for (let cookie of cookies) {
await removeCookie(cookie);
}
}
async function enableTrigger(tab, trigger) {
let host = getHost(tab.url);
let scope = await getScope(host);
let details = {
url: tab.url,
name: trigger.name,
value: trigger.value,
path: '/',
storeId: await getStoreId(tab)
};
if (scope) {
details.domain = scope;
}
await requireApi('cookies.set', [details]);
log('set', trigger.name + '=' + trigger.value, 'for', scope ? '.' + scope : host, 'store', details.storeId);
}
// Returns new state (true - enabled). Throws on API errors.
async function toggleTrigger(tab, triggerId) {
if (!tab || !isSupportedUrl(tab.url)) {
log('toggleTrigger: skipped, unsupported url', tab && tab.url);
return false;
}
let triggers = await getTriggerSettings(getHost(tab.url));
let trigger = triggers.find(t => t.id === triggerId);
if (await getCookie(tab, trigger)) {
await disableTrigger(tab, trigger);
return false;
}
await enableTrigger(tab, trigger);
return true;
}
// Re-sets enabled cookies after scope change.
// triggerIds - triggers to (re)enable, by default the currently enabled ones.
async function reapplyTriggers(tab, triggerIds) {
let triggers = await getTriggerSettings(getHost(tab.url));
for (let trigger of triggers) {
let enabled = triggerIds ? triggerIds.includes(trigger.id) : !!await getCookie(tab, trigger);
if (enabled) {
await disableTrigger(tab, trigger);
await enableTrigger(tab, trigger);
}
}
}
async function getActiveTab() {
let tabs = await callApi('tabs.query', [{ active: true, currentWindow: true }], []);
// Firefox for Android shows the popup as a page in its own tab: then the active tab is the
// popup itself, and the site is the most recently used other tab
let ownTab = typeof document !== 'undefined' ? await callApi('tabs.getCurrent', [], undefined) : undefined;
if (ownTab && tabs[0] && tabs[0].id === ownTab.id) {
let others = (await callApi('tabs.query', [{}], [])).filter(tab => tab.id !== ownTab.id);
others.sort((a, b) => (b.lastAccessed || 0) - (a.lastAccessed || 0));
log('getActiveTab: popup is shown in a tab, using the last used tab', others[0] && others[0].url);
return others[0];
}
return tabs[0];
}