-
Notifications
You must be signed in to change notification settings - Fork 331
/
index.js
578 lines (486 loc) · 16.2 KB
/
index.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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/* @flow */
import nodeFs from 'fs';
import path from 'path';
import {promisify} from 'util';
import {default as defaultFxRunner} from 'fx-runner';
import FirefoxProfile, {copyFromUserProfile as defaultUserProfileCopier}
from 'firefox-profile';
import {fs} from 'mz';
import eventToPromise from 'event-to-promise';
import isDirectory from '../util/is-directory';
import {isErrorWithCode, UsageError, WebExtError} from '../errors';
import {getPrefs as defaultPrefGetter} from './preferences';
import {getManifestId} from '../util/manifest';
import {createLogger} from '../util/logger';
import {connect as defaultFirefoxConnector, REMOTE_PORT} from './remote';
// Import flow types
import type {FirefoxConnectorFn} from './remote';
import type {
PreferencesAppName,
PreferencesGetterFn,
FirefoxPreferences,
} from './preferences';
import type {ExtensionManifest} from '../util/manifest';
const log = createLogger(__filename);
const defaultAsyncFsStat = fs.stat.bind(fs);
export const defaultFirefoxEnv = {
XPCOM_DEBUG_BREAK: 'stack',
NS_TRACE_MALLOC_DISABLE_STACKS: '1',
};
// defaultRemotePortFinder types and implementation.
export type RemotePortFinderParams = {|
portToTry?: number,
retriesLeft?: number,
connectToFirefox?: FirefoxConnectorFn,
|};
export type RemotePortFinderFn =
(params?: RemotePortFinderParams) => Promise<number>;
export async function defaultRemotePortFinder(
{
portToTry = REMOTE_PORT,
retriesLeft = 10,
connectToFirefox = defaultFirefoxConnector,
}: RemotePortFinderParams = {}
): Promise<number> {
log.debug(`Checking if remote Firefox port ${portToTry} is available`);
let client;
while (retriesLeft >= 0) {
try {
client = await connectToFirefox(portToTry);
log.debug(`Remote Firefox port ${portToTry} is in use ` +
`(retries remaining: ${retriesLeft})`);
} catch (error) {
if (isErrorWithCode('ECONNREFUSED', error)) {
// The connection was refused so this port is good to use.
return portToTry;
}
throw error;
}
client.disconnect();
portToTry++;
retriesLeft--;
}
throw new WebExtError('Too many retries on port search');
}
// Declare the needed 'fx-runner' module flow types.
export type FirefoxRunnerParams = {|
binary: ?string,
profile?: string,
'new-instance'?: boolean,
'no-remote'?: boolean,
'foreground'?: boolean,
'listen': number,
'binary-args'?: Array<string> | string,
'env'?: {
[key: string]: string
},
'verbose'?: boolean,
|};
export interface FirefoxProcess extends events$EventEmitter {
stderr: events$EventEmitter;
stdout: events$EventEmitter;
kill: Function;
}
export type FirefoxRunnerResults = {|
process: FirefoxProcess,
binary: string,
args: Array<string>,
|}
export type FirefoxRunnerFn =
(params: FirefoxRunnerParams) => Promise<FirefoxRunnerResults>;
export type FirefoxInfo = {|
firefox: FirefoxProcess,
debuggerPort: number,
|}
// Run command types and implementaion.
export type FirefoxRunOptions = {|
fxRunner?: FirefoxRunnerFn,
findRemotePort?: RemotePortFinderFn,
firefoxBinary?: string,
binaryArgs?: Array<string>,
args?: Array<any>,
|};
/*
* Runs Firefox with the given profile object and resolves a promise on exit.
*/
export async function run(
profile: FirefoxProfile,
{
fxRunner = defaultFxRunner,
findRemotePort = defaultRemotePortFinder,
firefoxBinary, binaryArgs,
}: FirefoxRunOptions = {}
): Promise<FirefoxInfo> {
log.debug(`Running Firefox with profile at ${profile.path()}`);
const remotePort = await findRemotePort();
const results = await fxRunner({
// if this is falsey, fxRunner tries to find the default one.
'binary': firefoxBinary,
'binary-args': binaryArgs,
// This ensures a new instance of Firefox is created. It has nothing
// to do with the devtools remote debugger.
'no-remote': true,
'listen': remotePort,
'foreground': true,
'profile': profile.path(),
'env': {
...process.env,
...defaultFirefoxEnv,
},
'verbose': true,
});
const firefox = results.process;
log.debug(`Executing Firefox binary: ${results.binary}`);
log.debug(`Firefox args: ${results.args.join(' ')}`);
firefox.on('error', (error) => {
// TODO: show a nice error when it can't find Firefox.
// if (/No such file/.test(err) || err.code === 'ENOENT') {
log.error(`Firefox error: ${error}`);
throw error;
});
log.info(
'Use --verbose or open Tools > Web Developer > Browser Console ' +
'to see logging');
firefox.stderr.on('data', (data) => {
log.debug(`Firefox stderr: ${data.toString().trim()}`);
});
firefox.stdout.on('data', (data) => {
log.debug(`Firefox stdout: ${data.toString().trim()}`);
});
firefox.on('close', () => {
log.debug('Firefox closed');
});
return { firefox, debuggerPort: remotePort };
}
// isDefaultProfile types and implementation.
const DEFAULT_PROFILES_NAMES = [
'default',
'dev-edition-default',
];
export type IsDefaultProfileFn = (
profilePathOrName: string,
ProfileFinder?: typeof FirefoxProfile.Finder,
fsStat?: typeof fs.stat,
) => Promise<boolean>;
/*
* Tests if a profile is a default Firefox profile (both as a profile name or
* profile path).
*
* Returns a promise that resolves to true if the profile is one of default Firefox profile.
*/
export async function isDefaultProfile(
profilePathOrName: string,
ProfileFinder?: typeof FirefoxProfile.Finder = FirefoxProfile.Finder,
fsStat?: typeof fs.stat = fs.stat,
): Promise<boolean> {
if (DEFAULT_PROFILES_NAMES.includes(profilePathOrName)) {
return true;
}
const baseProfileDir = ProfileFinder.locateUserDirectory();
const profilesIniPath = path.join(baseProfileDir, 'profiles.ini');
try {
await fsStat(profilesIniPath);
} catch (error) {
if (isErrorWithCode('ENOENT', error)) {
log.debug(`profiles.ini not found: ${error}`);
// No profiles exist yet, default to false (the default profile name contains a
// random generated component).
return false;
}
// Re-throw any unexpected exception.
throw error;
}
// Check for profile dir path.
const finder = new ProfileFinder(baseProfileDir);
const readProfiles = promisify(finder.readProfiles.bind(finder));
await readProfiles();
const normalizedProfileDirPath = path.normalize(
path.join(path.resolve(profilePathOrName), path.sep)
);
for (const profile of finder.profiles) {
// Check if the profile dir path or name is one of the default profiles
// defined in the profiles.ini file.
if (DEFAULT_PROFILES_NAMES.includes(profile.Name) ||
profile.Default === '1') {
let profileFullPath;
// Check for profile name.
if (profile.Name === profilePathOrName) {
return true;
}
// Check for profile path.
if (profile.IsRelative === '1') {
profileFullPath = path.join(baseProfileDir, profile.Path, path.sep);
} else {
profileFullPath = path.join(profile.Path, path.sep);
}
if (path.normalize(profileFullPath) === normalizedProfileDirPath) {
return true;
}
}
}
// Profile directory not found.
return false;
}
// configureProfile types and implementation.
export type ConfigureProfileOptions = {|
app?: PreferencesAppName,
getPrefs?: PreferencesGetterFn,
customPrefs?: FirefoxPreferences,
|};
export type ConfigureProfileFn = (
profile: FirefoxProfile,
options?: ConfigureProfileOptions
) => Promise<FirefoxProfile>;
/*
* Configures a profile with common preferences that are required to
* activate extension development.
*
* Returns a promise that resolves with the original profile object.
*/
export function configureProfile(
profile: FirefoxProfile,
{
app = 'firefox',
getPrefs = defaultPrefGetter,
customPrefs = {},
}: ConfigureProfileOptions = {},
): Promise<FirefoxProfile> {
// Set default preferences. Some of these are required for the add-on to
// operate, such as disabling signatures.
const prefs = getPrefs(app);
Object.keys(prefs).forEach((pref) => {
profile.setPreference(pref, prefs[pref]);
});
if (Object.keys(customPrefs).length > 0) {
const customPrefsStr = JSON.stringify(customPrefs, null, 2);
log.info(`Setting custom Firefox preferences: ${customPrefsStr}`);
Object.keys(customPrefs).forEach((custom) => {
profile.setPreference(custom, customPrefs[custom]);
});
}
profile.updatePreferences();
return Promise.resolve(profile);
}
export type getProfileFn = (profileName: string) => Promise<string | void>;
export type CreateProfileFinderParams = {|
userDirectoryPath?: string,
FxProfile?: typeof FirefoxProfile
|}
export function defaultCreateProfileFinder(
{
userDirectoryPath,
FxProfile = FirefoxProfile,
}: CreateProfileFinderParams = {}
): getProfileFn {
const finder = new FxProfile.Finder(userDirectoryPath);
const readProfiles = promisify(finder.readProfiles.bind(finder));
const getPath = promisify(finder.getPath.bind(finder));
return async (profileName: string): Promise<string | void> => {
try {
await readProfiles();
const hasProfileName = finder.profiles.filter(
(profileDef) => profileDef.Name === profileName).length !== 0;
if (hasProfileName) {
return await getPath(profileName);
}
} catch (error) {
if (!isErrorWithCode('ENOENT', error)) {
throw error;
}
log.warn('Unable to find Firefox profiles.ini');
}
};
}
// useProfile types and implementation.
export type UseProfileParams = {
app?: PreferencesAppName,
configureThisProfile?: ConfigureProfileFn,
isFirefoxDefaultProfile?: IsDefaultProfileFn,
customPrefs?: FirefoxPreferences,
createProfileFinder?: typeof defaultCreateProfileFinder,
};
// Use the target path as a Firefox profile without cloning it
export async function useProfile(
profilePath: string,
{
app,
configureThisProfile = configureProfile,
isFirefoxDefaultProfile = isDefaultProfile,
customPrefs = {},
createProfileFinder = defaultCreateProfileFinder,
}: UseProfileParams = {},
): Promise<FirefoxProfile> {
const isForbiddenProfile = await isFirefoxDefaultProfile(profilePath);
if (isForbiddenProfile) {
throw new UsageError(
'Cannot use --keep-profile-changes on a default profile' +
` ("${profilePath}")` +
' because web-ext will make it insecure and unsuitable for daily use.' +
'\nSee https://github.com/mozilla/web-ext/issues/1005'
);
}
let destinationDirectory;
const getProfilePath = createProfileFinder();
const profileIsDirPath = await isDirectory(profilePath);
if (profileIsDirPath) {
log.debug(`Using profile directory "${profilePath}"`);
destinationDirectory = profilePath;
} else {
log.debug(`Assuming ${profilePath} is a named profile`);
destinationDirectory = await getProfilePath(profilePath);
if (!destinationDirectory) {
throw new UsageError(
`The request "${profilePath}" profile name ` +
'cannot be resolved to a profile path'
);
}
}
const profile = new FirefoxProfile({destinationDirectory});
return await configureThisProfile(profile, {app, customPrefs});
}
// createProfile types and implementation.
export type CreateProfileParams = {
app?: PreferencesAppName,
configureThisProfile?: ConfigureProfileFn,
customPrefs?: FirefoxPreferences,
};
/*
* Creates a new temporary profile and resolves with the profile object.
*
* The profile will be deleted when the system process exits.
*/
export async function createProfile(
{
app,
configureThisProfile = configureProfile,
customPrefs = {},
}: CreateProfileParams = {},
): Promise<FirefoxProfile> {
const profile = new FirefoxProfile();
return await configureThisProfile(profile, {app, customPrefs});
}
// copyProfile types and implementation.
export type CopyProfileOptions = {|
app?: PreferencesAppName,
configureThisProfile?: ConfigureProfileFn,
copyFromUserProfile?: Function,
customPrefs?: FirefoxPreferences,
|};
/*
* Copies an existing Firefox profile and creates a new temporary profile.
* The new profile will be configured with some preferences required to
* activate extension development.
*
* It resolves with the new profile object.
*
* The temporary profile will be deleted when the system process exits.
*
* The existing profile can be specified as a directory path or a name of
* one that exists in the current user's Firefox directory.
*/
export async function copyProfile(
profileDirectory: string,
{
app,
configureThisProfile = configureProfile,
copyFromUserProfile = defaultUserProfileCopier,
customPrefs = {},
}: CopyProfileOptions = {},
): Promise<FirefoxProfile> {
const copy = promisify(FirefoxProfile.copy);
const copyByName = promisify(copyFromUserProfile);
try {
const dirExists = await isDirectory(profileDirectory);
let profile;
if (dirExists) {
log.debug(`Copying profile directory from "${profileDirectory}"`);
profile = await copy({profileDirectory});
} else {
log.debug(`Assuming ${profileDirectory} is a named profile`);
profile = await copyByName({name: profileDirectory});
}
return configureThisProfile(profile, {app, customPrefs});
} catch (error) {
throw new WebExtError(
`Could not copy Firefox profile from ${profileDirectory}: ${error}`);
}
}
// installExtension types and implementation.
export type InstallExtensionParams = {|
asProxy?: boolean,
manifestData: ExtensionManifest,
profile: FirefoxProfile,
extensionPath: string,
asyncFsStat?: typeof defaultAsyncFsStat,
|};
/*
* Installs an extension into the given Firefox profile object.
* Resolves when complete.
*
* The extension is copied into a special location and you need to turn
* on some preferences to allow this. See extensions.autoDisableScopes in
* ./preferences.js.
*
* When asProxy is true, a special proxy file will be installed. This is a
* text file that contains the path to the extension source.
*/
export async function installExtension(
{
asProxy = false,
manifestData,
profile,
extensionPath,
asyncFsStat = defaultAsyncFsStat,
}: InstallExtensionParams): Promise<any> {
// This more or less follows
// https://github.com/saadtazi/firefox-profile-js/blob/master/lib/firefox_profile.js#L531
// (which is broken for web extensions).
// TODO: maybe uplift a patch that supports web extensions instead?
if (!profile.extensionsDir) {
throw new WebExtError('profile.extensionsDir was unexpectedly empty');
}
try {
await asyncFsStat(profile.extensionsDir);
} catch (error) {
if (isErrorWithCode('ENOENT', error)) {
log.debug(`Creating extensions directory: ${profile.extensionsDir}`);
await fs.mkdir(profile.extensionsDir);
} else {
throw error;
}
}
const id = getManifestId(manifestData);
if (!id) {
throw new UsageError(
'An explicit extension ID is required when installing to ' +
'a profile (applications.gecko.id not found in manifest.json)');
}
if (asProxy) {
log.debug(`Installing as an extension proxy; source: ${extensionPath}`);
const isDir = await isDirectory(extensionPath);
if (!isDir) {
throw new WebExtError(
'proxy install: extensionPath must be the extension source ' +
`directory; got: ${extensionPath}`);
}
// Write a special extension proxy file containing the source
// directory. See:
// https://developer.mozilla.org/en-US/Add-ons/Setting_up_extension_development_environment#Firefox_extension_proxy_file
const destPath = path.join(profile.extensionsDir, `${id}`);
const writeStream = nodeFs.createWriteStream(destPath);
writeStream.write(extensionPath);
writeStream.end();
return await eventToPromise(writeStream, 'close');
} else {
// Write the XPI file to the profile.
const readStream = nodeFs.createReadStream(extensionPath);
const destPath = path.join(profile.extensionsDir, `${id}.xpi`);
const writeStream = nodeFs.createWriteStream(destPath);
log.debug(`Installing extension from ${extensionPath} to ${destPath}`);
readStream.pipe(writeStream);
return await Promise.all([
eventToPromise(readStream, 'close'),
eventToPromise(writeStream, 'close'),
]);
}
}