Charles Lyding 0e6425fd88 feat(@angular-devkit/schematics): disable package script execution by default in NodePackageInstallTask
In an effort to improve supply chain security, the `NodePackageInstallTask` will now use the package
manager's `--ignore-scripts` option by default. Without the option, all direct and transitive
dependencies would have their scripts executed during the task's package manager installation operation.
The change only affects the package manager behavior controlled by the Schematics `NodePackageInstallTask`.

First-party Angular schematics do not currently require any direct or transitive dependency
`install`/`postinstall` scripts to execute. Only two dependencies within a v14.0 new project would
potentially be affected by this: `nice-napi` (transitive from `piscina`) and `esbuild`. The `nice-napi`
functionality of `piscina` is unused within the Angular CLI with no plans to use it in the future.
Even if it was used, the `install` script runs `node-gyp-build` which would only have an effect
(based on the current version 1.0.2) on platforms that are not Windows, darwin-x64, or linux-x64.
In the event this functionality is eventually used, the Angular CLI could be setup to automatically execute
this particular script for unsupported platforms. For `esbuild`, the `postinstall` functionality
performs an optional native binary bootstrap optimization but would only be performed if not
using Windows or Yarn. As such, it would not be performed for many users regardless of the change in
this commit. If noticeable performance regressions on platforms where the optimization was previously
performed are reported, the script could also be setup to be automatically run by the Angular CLI during
project creation and/or first build.

BREAKING CHANGE: Schematics `NodePackageInstallTask` will not execute package scripts by default
The `NodePackageInstallTask` will now use the package manager's `--ignore-scripts` option by default.
The `--ignore-scripts` option will prevent package scripts from executing automatically during an install.
If a schematic installs packages that need their `install`/`postinstall` scripts to be executed, the
`NodePackageInstallTask` now contains an `allowScripts` boolean option which can be enabled to provide the
previous behavior for that individual task. As with previous behavior, the `allowScripts` option will
prevent the individual task's usage of the `--ignore-scripts` option but will not override the package
manager's existing configuration.
2022-04-29 16:37:56 -07:00

149 lines
4.5 KiB
TypeScript

/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { BaseException } from '@angular-devkit/core';
import { SpawnOptions, spawn } from 'child_process';
import ora from 'ora';
import * as path from 'path';
import { Observable } from 'rxjs';
import { TaskExecutor, UnsuccessfulWorkflowExecution } from '../../src';
import { NodePackageTaskFactoryOptions, NodePackageTaskOptions } from './options';
interface PackageManagerProfile {
quietArgument?: string;
commands: {
installAll?: string;
installPackage: string;
};
}
const packageManagers: { [name: string]: PackageManagerProfile } = {
'npm': {
quietArgument: '--quiet',
commands: {
installAll: 'install',
installPackage: 'install',
},
},
'cnpm': {
commands: {
installAll: 'install',
installPackage: 'install',
},
},
'yarn': {
quietArgument: '--silent',
commands: {
installPackage: 'add',
},
},
'pnpm': {
quietArgument: '--silent',
commands: {
installAll: 'install',
installPackage: 'install',
},
},
};
export class UnknownPackageManagerException extends BaseException {
constructor(name: string) {
super(`Unknown package manager "${name}".`);
}
}
export default function (
factoryOptions: NodePackageTaskFactoryOptions = {},
): TaskExecutor<NodePackageTaskOptions> {
const packageManagerName = factoryOptions.packageManager || 'npm';
const packageManagerProfile = packageManagers[packageManagerName];
if (!packageManagerProfile) {
throw new UnknownPackageManagerException(packageManagerName);
}
const rootDirectory = factoryOptions.rootDirectory || process.cwd();
return (options: NodePackageTaskOptions = { command: 'install' }) => {
let taskPackageManagerProfile = packageManagerProfile;
let taskPackageManagerName = packageManagerName;
if (factoryOptions.allowPackageManagerOverride && options.packageManager) {
taskPackageManagerProfile = packageManagers[options.packageManager];
if (!taskPackageManagerProfile) {
throw new UnknownPackageManagerException(options.packageManager);
}
taskPackageManagerName = options.packageManager;
}
const bufferedOutput: { stream: NodeJS.WriteStream; data: Buffer }[] = [];
const spawnOptions: SpawnOptions = {
stdio: options.hideOutput ? 'pipe' : 'inherit',
shell: true,
cwd: path.join(rootDirectory, options.workingDirectory || ''),
};
const args: string[] = [];
if (options.packageName) {
if (options.command === 'install') {
args.push(taskPackageManagerProfile.commands.installPackage);
}
args.push(options.packageName);
} else if (options.command === 'install' && taskPackageManagerProfile.commands.installAll) {
args.push(taskPackageManagerProfile.commands.installAll);
}
if (options.quiet && taskPackageManagerProfile.quietArgument) {
args.push(taskPackageManagerProfile.quietArgument);
}
if (!options.allowScripts) {
args.push('--ignore-scripts');
}
if (factoryOptions.registry) {
args.push(`--registry="${factoryOptions.registry}"`);
}
if (factoryOptions.force) {
args.push('--force');
}
return new Observable((obs) => {
const spinner = ora({
text: `Installing packages (${taskPackageManagerName})...`,
// Workaround for https://github.com/sindresorhus/ora/issues/136.
discardStdin: process.platform != 'win32',
}).start();
const childProcess = spawn(taskPackageManagerName, args, spawnOptions).on(
'close',
(code: number) => {
if (code === 0) {
spinner.succeed('Packages installed successfully.');
spinner.stop();
obs.next();
obs.complete();
} else {
if (options.hideOutput) {
bufferedOutput.forEach(({ stream, data }) => stream.write(data));
}
spinner.fail('Package install failed, see above.');
obs.error(new UnsuccessfulWorkflowExecution());
}
},
);
if (options.hideOutput) {
childProcess.stdout?.on('data', (data: Buffer) =>
bufferedOutput.push({ stream: process.stdout, data: data }),
);
childProcess.stderr?.on('data', (data: Buffer) =>
bufferedOutput.push({ stream: process.stderr, data: data }),
);
}
});
};
}