import IPuppetBrowser from '@secret-agent/interfaces/IPuppetBrowser';
import ILaunchedProcess from '@secret-agent/interfaces/ILaunchedProcess';
import IPuppetLauncher from '@secret-agent/interfaces/IPuppetLauncher';
import * as os from 'os';
import IBrowserEngine from '@secret-agent/interfaces/IBrowserEngine';
import { IPuppetLaunchError } from '@secret-agent/interfaces/IPuppetLaunchError';
import IPuppetLaunchArgs from '@secret-agent/interfaces/IPuppetLaunchArgs';
import { Browser } from './lib/Browser';
import { Connection } from './lib/Connection';
const PuppetLauncher: IPuppetLauncher = {
getLaunchArgs(options: IPuppetLaunchArgs, browserEngine: IBrowserEngine) {
const chromeArguments = browserEngine.launchArguments ?? [];
if (options.proxyPort !== undefined) {
chromeArguments.push(
'--proxy-bypass-list=<-loopback>',
`--proxy-server=localhost:${options.proxyPort}`,
);
}
chromeArguments.push('--remote-debugging-pipe', '--ignore-certificate-errors');
if (options.noChromeSandbox === true) {
chromeArguments.push('--no-sandbox');
} else if (os.platform() === 'linux') {
const runningAsRoot = process.geteuid && process.geteuid() === 0;
if (runningAsRoot) {
console.warn(
'WARNING: Secret-Agent is being run under "root" user - disabling Chrome sandbox! ' +
'Run under regular user to get rid of this warning.',
);
chromeArguments.push('--no-sandbox');
}
}
browserEngine.isHeaded = options.showBrowser === true;
if (!browserEngine.isHeaded) {
chromeArguments.push('--headless');
}
if (browserEngine.beforeLaunch) browserEngine.beforeLaunch(options);
return browserEngine.launchArguments;
},
async createPuppet(
process: ILaunchedProcess,
browserEngine: IBrowserEngine,
): Promise<IPuppetBrowser> {
const { transport, close } = process;
try {
const connection = new Connection(transport);
return await Browser.create(connection, browserEngine, close);
} catch (error) {
await close();
throw error;
}
},
translateLaunchError(rawError: Error): IPuppetLaunchError {
const error = {
message: rawError.message,
stack: rawError.stack,
name: 'PuppetLaunchError',
isSandboxError: false,
};
if (
error.message.includes('crbug.com/357670') ||
error.message.includes('No usable sandbox!') ||
error.message.includes('crbug.com/638180')
) {
error.stack += [
`\nChrome sandboxing failed!`,
`================================`,
`To workaround sandboxing issues, do either of the following:`,
` - (preferred): Configure environment to support sandboxing (as here: https://github.com/ulixee/secret-agent/tree/master/tools/docker)`,
` - (alternative): Launch Chrome without sandbox using 'SA_NO_CHROME_SANDBOX=false' environmental variable`,
`================================`,
``,
].join('\n');
error.isSandboxError = true;
}
return error;
},
};
export default PuppetLauncher;