mirror of
https://github.com/AikidoSec/safe-chain.git
synced 2026-05-26 12:10:49 +00:00
Type check safe-chain package
This commit is contained in:
parent
d5dc801c00
commit
c88b1a624f
60 changed files with 1179 additions and 33 deletions
|
|
@ -29,7 +29,7 @@ export const scanner = {
|
|||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
console.warn(`Safe-Chain security scan failed: ${error.message}`);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,4 +7,5 @@ const packageManagerName = "bun";
|
|||
initializePackageManager(packageManagerName);
|
||||
var exitCode = await main(process.argv.slice(2));
|
||||
|
||||
// @ts-expect-error scanCommand can return an empty array in main
|
||||
process.exit(exitCode);
|
||||
|
|
|
|||
|
|
@ -7,4 +7,5 @@ const packageManagerName = "bunx";
|
|||
initializePackageManager(packageManagerName);
|
||||
var exitCode = await main(process.argv.slice(2));
|
||||
|
||||
// @ts-expect-error scanCommand can return an empty array in main
|
||||
process.exit(exitCode);
|
||||
|
|
|
|||
|
|
@ -7,4 +7,5 @@ const packageManagerName = "npm";
|
|||
initializePackageManager(packageManagerName);
|
||||
var exitCode = await main(process.argv.slice(2));
|
||||
|
||||
// @ts-expect-error scanCommand can return an empty array in main
|
||||
process.exit(exitCode);
|
||||
|
|
|
|||
|
|
@ -7,4 +7,5 @@ const packageManagerName = "npx";
|
|||
initializePackageManager(packageManagerName);
|
||||
var exitCode = await main(process.argv.slice(2));
|
||||
|
||||
// @ts-expect-error scanCommand can return an empty array in main
|
||||
process.exit(exitCode);
|
||||
|
|
|
|||
|
|
@ -7,4 +7,5 @@ const packageManagerName = "pnpm";
|
|||
initializePackageManager(packageManagerName);
|
||||
var exitCode = await main(process.argv.slice(2));
|
||||
|
||||
// @ts-expect-error scanCommand can return an empty array in main
|
||||
process.exit(exitCode);
|
||||
|
|
|
|||
|
|
@ -7,4 +7,5 @@ const packageManagerName = "pnpx";
|
|||
initializePackageManager(packageManagerName);
|
||||
var exitCode = await main(process.argv.slice(2));
|
||||
|
||||
// @ts-expect-error scanCommand can return an empty array in main
|
||||
process.exit(exitCode);
|
||||
|
|
|
|||
|
|
@ -7,4 +7,5 @@ const packageManagerName = "yarn";
|
|||
initializePackageManager(packageManagerName);
|
||||
var exitCode = await main(process.argv.slice(2));
|
||||
|
||||
// @ts-expect-error scanCommand can return an empty array in main
|
||||
process.exit(exitCode);
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@
|
|||
"scripts": {
|
||||
"test": "node --test --experimental-test-module-mocks 'src/**/*.spec.js'",
|
||||
"test:watch": "node --test --watch --experimental-test-module-mocks 'src/**/*.spec.js'",
|
||||
"lint": "oxlint --deny-warnings"
|
||||
"lint": "oxlint --deny-warnings",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"bin": {
|
||||
"aikido-npm": "bin/aikido-npm.js",
|
||||
|
|
@ -38,6 +39,14 @@
|
|||
"ora": "8.2.0",
|
||||
"semver": "7.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/make-fetch-happen": "^10.0.4",
|
||||
"@types/node": "^24.9.2",
|
||||
"@types/npm-registry-fetch": "^8.0.9",
|
||||
"@types/semver": "^7.7.1",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"main": "src/main.js",
|
||||
"bugs": {
|
||||
"url": "https://github.com/AikidoSec/safe-chain/issues"
|
||||
|
|
|
|||
|
|
@ -3,6 +3,16 @@ import fetch from "make-fetch-happen";
|
|||
const malwareDatabaseUrl =
|
||||
"https://malware-list.aikido.dev/malware_predictions.json";
|
||||
|
||||
/**
|
||||
* @typedef MalwarePackage
|
||||
* @property {string} package_name
|
||||
* @property {string} version
|
||||
* @property {string} reason
|
||||
*/
|
||||
|
||||
/**
|
||||
* @returns {Promise<{malwareDatabase: MalwarePackage[], version: string | undefined}>}
|
||||
*/
|
||||
export async function fetchMalwareDatabase() {
|
||||
const response = await fetch(malwareDatabaseUrl);
|
||||
if (!response.ok) {
|
||||
|
|
@ -15,11 +25,14 @@ export async function fetchMalwareDatabase() {
|
|||
malwareDatabase: malwareDatabase,
|
||||
version: response.headers.get("etag") || undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
} catch (/** @type {any} */ error) {
|
||||
throw new Error(`Error parsing malware database: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<string | undefined>}
|
||||
*/
|
||||
export async function fetchMalwareDatabaseVersion() {
|
||||
const response = await fetch(malwareDatabaseUrl, {
|
||||
method: "HEAD",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,11 @@
|
|||
import * as semver from "semver";
|
||||
import * as npmFetch from "npm-registry-fetch";
|
||||
|
||||
/**
|
||||
* @param {string} packageName
|
||||
* @param {string | null} [versionRange]
|
||||
* @returns {Promise<string | null>}
|
||||
*/
|
||||
export async function resolvePackageVersion(packageName, versionRange) {
|
||||
if (!versionRange) {
|
||||
versionRange = "latest";
|
||||
|
|
@ -11,7 +16,10 @@ export async function resolvePackageVersion(packageName, versionRange) {
|
|||
return versionRange;
|
||||
}
|
||||
|
||||
const packageInfo = await getPackageInfo(packageName);
|
||||
const packageInfo = (
|
||||
/** @type {{"dist-tags"?: Record<string, string>} | null} */
|
||||
await getPackageInfo(packageName)
|
||||
);
|
||||
if (!packageInfo) {
|
||||
// It is possible that no version is found (could be a private package, or a package that doesn't exist)
|
||||
// In this case, we return null to indicate that we couldn't resolve the version
|
||||
|
|
@ -19,7 +27,7 @@ export async function resolvePackageVersion(packageName, versionRange) {
|
|||
}
|
||||
|
||||
const distTags = packageInfo["dist-tags"];
|
||||
if (distTags && distTags[versionRange]) {
|
||||
if (distTags && isDistTags(distTags)) {
|
||||
// If the version range is a dist-tag, return the version associated with that tag
|
||||
// e.g., "latest", "next", etc.
|
||||
return distTags[versionRange];
|
||||
|
|
@ -41,6 +49,19 @@ export async function resolvePackageVersion(packageName, versionRange) {
|
|||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {unknown} distTags
|
||||
* @returns {distTags is Record<string, string>}
|
||||
*/
|
||||
function isDistTags(distTags) {
|
||||
return typeof distTags === "object";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} packageName
|
||||
* @returns {Promise<Record<string, unknown> | null>}
|
||||
*/
|
||||
async function getPackageInfo(packageName) {
|
||||
try {
|
||||
return await npmFetch.json(packageName);
|
||||
|
|
|
|||
|
|
@ -1,9 +1,16 @@
|
|||
/**
|
||||
* @type {{loggingLevel: string | undefined}}
|
||||
*/
|
||||
const state = {
|
||||
loggingLevel: undefined,
|
||||
};
|
||||
|
||||
const SAFE_CHAIN_ARG_PREFIX = "--safe-chain-";
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function initializeCliArguments(args) {
|
||||
// Reset state on each call
|
||||
state.loggingLevel = undefined;
|
||||
|
|
@ -24,6 +31,11 @@ export function initializeCliArguments(args) {
|
|||
return remainingArgs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @param {string} prefix
|
||||
* @returns {string | undefined}
|
||||
*/
|
||||
function getLastArgEqualsValue(args, prefix) {
|
||||
for (var i = args.length - 1; i >= 0; i--) {
|
||||
const arg = args[i];
|
||||
|
|
@ -35,6 +47,10 @@ function getLastArgEqualsValue(args, prefix) {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {void}
|
||||
*/
|
||||
function setLoggingLevel(args) {
|
||||
const safeChainLoggingArg = SAFE_CHAIN_ARG_PREFIX + "logging=";
|
||||
|
||||
|
|
|
|||
|
|
@ -3,13 +3,46 @@ import path from "path";
|
|||
import os from "os";
|
||||
import { ui } from "../environment/userInteraction.js";
|
||||
|
||||
/**
|
||||
* @returns {number}
|
||||
*/
|
||||
export function getScanTimeout() {
|
||||
if (process.env.AIKIDO_SCAN_TIMEOUT_MS) {
|
||||
const timeout = parseInt(process.env.AIKIDO_SCAN_TIMEOUT_MS);
|
||||
if (!isNaN(timeout) && timeout >= 0) {
|
||||
return timeout;
|
||||
}
|
||||
}
|
||||
|
||||
const config = readConfigFile();
|
||||
|
||||
if (hasScanTimeout(config) && config.scanTimeout >= 0) {
|
||||
return config.scanTimeout;
|
||||
}
|
||||
|
||||
return 10000; // Default to 10 seconds
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {unknown} config
|
||||
*
|
||||
* @returns {config is {scanTimeout: number}}
|
||||
*/
|
||||
function hasScanTimeout(config) {
|
||||
return (
|
||||
parseInt(process.env.AIKIDO_SCAN_TIMEOUT_MS) || config.scanTimeout || 10000 // Default to 10 seconds
|
||||
typeof config === "object" &&
|
||||
config !== null &&
|
||||
"scanTimeout" in config &&
|
||||
typeof config.scanTimeout === "number"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("../api/aikido.js").MalwarePackage[]} data
|
||||
* @param {string | number} version
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
export function writeDatabaseToLocalCache(data, version) {
|
||||
try {
|
||||
const databasePath = getDatabasePath();
|
||||
|
|
@ -24,6 +57,9 @@ export function writeDatabaseToLocalCache(data, version) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {{malwareDatabase: import("../api/aikido.js").MalwarePackage[] | null, version: string | null}}
|
||||
*/
|
||||
export function readDatabaseFromLocalCache() {
|
||||
try {
|
||||
const databasePath = getDatabasePath();
|
||||
|
|
@ -55,6 +91,9 @@ export function readDatabaseFromLocalCache() {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {unknown}
|
||||
*/
|
||||
function readConfigFile() {
|
||||
const configFilePath = getConfigFilePath();
|
||||
|
||||
|
|
@ -66,20 +105,30 @@ function readConfigFile() {
|
|||
return JSON.parse(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string}
|
||||
*/
|
||||
function getDatabasePath() {
|
||||
const aikidoDir = getAikidoDirectory();
|
||||
return path.join(aikidoDir, "malwareDatabase.json");
|
||||
}
|
||||
|
||||
|
||||
function getDatabaseVersionPath() {
|
||||
const aikidoDir = getAikidoDirectory();
|
||||
return path.join(aikidoDir, "version.txt");
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string}
|
||||
*/
|
||||
function getConfigFilePath() {
|
||||
return path.join(getAikidoDirectory(), "config.json");
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string}
|
||||
*/
|
||||
function getAikidoDirectory() {
|
||||
const homeDir = os.homedir();
|
||||
const aikidoDir = path.join(homeDir, ".aikido");
|
||||
|
|
|
|||
|
|
@ -14,12 +14,22 @@ function emptyLine() {
|
|||
writeInformation("");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} message
|
||||
* @param {...any} optionalParams
|
||||
* @returns {void}
|
||||
*/
|
||||
function writeInformation(message, ...optionalParams) {
|
||||
if (isSilentMode()) return;
|
||||
|
||||
console.log(message, ...optionalParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} message
|
||||
* @param {...any} optionalParams
|
||||
* @returns {void}
|
||||
*/
|
||||
function writeWarning(message, ...optionalParams) {
|
||||
if (isSilentMode()) return;
|
||||
|
||||
|
|
@ -29,6 +39,11 @@ function writeWarning(message, ...optionalParams) {
|
|||
console.warn(message, ...optionalParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} message
|
||||
* @param {...any} optionalParams
|
||||
* @returns {void}
|
||||
*/
|
||||
function writeError(message, ...optionalParams) {
|
||||
if (!isCi()) {
|
||||
message = chalk.red(message);
|
||||
|
|
@ -44,6 +59,19 @@ function writeExitWithoutInstallingMaliciousPackages() {
|
|||
console.error(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef Spinner
|
||||
* @property {(message: string) => void} succeed
|
||||
* @property {(message: string) => void} fail
|
||||
* @property {() => void} stop
|
||||
* @property {(message: string) => void} setText
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} message
|
||||
*
|
||||
* @returns {Spinner}
|
||||
*/
|
||||
function startProcess(message) {
|
||||
if (isSilentMode()) {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -7,6 +7,10 @@ import { initializeCliArguments } from "./config/cliArguments.js";
|
|||
import { createSafeChainProxy } from "./registryProxy/registryProxy.js";
|
||||
import chalk from "chalk";
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {Promise<number | never[]>}
|
||||
*/
|
||||
export async function main(args) {
|
||||
const proxy = createSafeChainProxy();
|
||||
await proxy.startServer();
|
||||
|
|
@ -14,6 +18,7 @@ export async function main(args) {
|
|||
// Global error handlers to log unhandled errors
|
||||
process.on("uncaughtException", (error) => {
|
||||
ui.writeError(`Safe-chain: Uncaught exception: ${error.message}`);
|
||||
// @ts-expect-error writeVerbose will be added in a future PR
|
||||
ui.writeVerbose(`Stack trace: ${error.stack}`);
|
||||
process.exit(1);
|
||||
});
|
||||
|
|
@ -21,6 +26,7 @@ export async function main(args) {
|
|||
process.on("unhandledRejection", (reason) => {
|
||||
ui.writeError(`Safe-chain: Unhandled promise rejection: ${reason}`);
|
||||
if (reason instanceof Error) {
|
||||
// @ts-expect-error writeVerbose will be added in a future PR
|
||||
ui.writeVerbose(`Stack trace: ${reason.stack}`);
|
||||
}
|
||||
process.exit(1);
|
||||
|
|
@ -56,7 +62,7 @@ export async function main(args) {
|
|||
// Returning the exit code back to the caller allows the promise
|
||||
// to be awaited in the bin files and return the correct exit code
|
||||
return packageManagerResult.status;
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
ui.writeError("Failed to check for malicious packages:", error.message);
|
||||
|
||||
// Returning the exit code back to the caller allows the promise
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @param {string[]} args
|
||||
* @param {...string} commandArgs
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function matchesCommand(args, ...commandArgs) {
|
||||
if (args.length < commandArgs.length) {
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,9 @@ import { ui } from "../../environment/userInteraction.js";
|
|||
import { safeSpawn } from "../../utils/safeSpawn.js";
|
||||
import { mergeSafeChainProxyEnvironmentVariables } from "../../registryProxy/registryProxy.js";
|
||||
|
||||
/**
|
||||
* @returns {import("../currentPackageManager.js").PackageManager}
|
||||
*/
|
||||
export function createBunPackageManager() {
|
||||
return {
|
||||
runCommand: (args) => runBunCommand("bun", args),
|
||||
|
|
@ -9,10 +12,13 @@ export function createBunPackageManager() {
|
|||
// For bun, we use the proxy-only approach to block package downloads,
|
||||
// so we don't need to analyze commands.
|
||||
isSupportedCommand: () => false,
|
||||
getDependencyUpdatesForCommand: () => [],
|
||||
getDependencyUpdatesForCommand: async () => [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {import("../currentPackageManager.js").PackageManager}
|
||||
*/
|
||||
export function createBunxPackageManager() {
|
||||
return {
|
||||
runCommand: (args) => runBunCommand("bunx", args),
|
||||
|
|
@ -20,18 +26,24 @@ export function createBunxPackageManager() {
|
|||
// For bunx, we use the proxy-only approach to block package downloads,
|
||||
// so we don't need to analyze commands.
|
||||
isSupportedCommand: () => false,
|
||||
getDependencyUpdatesForCommand: () => [],
|
||||
getDependencyUpdatesForCommand: async () => [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} command
|
||||
* @param {string[]} args
|
||||
* @returns {Promise<{status: number}>}
|
||||
*/
|
||||
async function runBunCommand(command, args) {
|
||||
try {
|
||||
const result = await safeSpawn(command, args, {
|
||||
stdio: "inherit",
|
||||
// @ts-expect-error values of process.env can be string | undefined
|
||||
env: mergeSafeChainProxyEnvironmentVariables(process.env),
|
||||
});
|
||||
return { status: result.status };
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
if (error.status) {
|
||||
return { status: error.status };
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -10,10 +10,25 @@ import {
|
|||
} from "./pnpm/createPackageManager.js";
|
||||
import { createYarnPackageManager } from "./yarn/createPackageManager.js";
|
||||
|
||||
/**
|
||||
* @type {{packageManagerName: PackageManager | null}}
|
||||
*/
|
||||
const state = {
|
||||
packageManagerName: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef PackageManager
|
||||
* @property {(args: string[]) => Promise<{ status: number }>} runCommand
|
||||
* @property {(args: string[]) => boolean} isSupportedCommand
|
||||
* @property {(args: string[]) => Promise<{name: string, version: string, type: string}[]>} getDependencyUpdatesForCommand
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} packageManagerName
|
||||
*
|
||||
* @return {PackageManager}
|
||||
*/
|
||||
export function initializePackageManager(packageManagerName) {
|
||||
if (packageManagerName === "npm") {
|
||||
state.packageManagerName = createNpmPackageManager();
|
||||
|
|
|
|||
|
|
@ -8,7 +8,15 @@ import {
|
|||
npmExecCommand,
|
||||
} from "./utils/npmCommands.js";
|
||||
|
||||
/**
|
||||
* @returns {import("../currentPackageManager.js").PackageManager}
|
||||
*/
|
||||
export function createNpmPackageManager() {
|
||||
/**
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isSupportedCommand(args) {
|
||||
const scanner = findDependencyScannerForCommand(
|
||||
commandScannerMapping,
|
||||
|
|
@ -17,6 +25,11 @@ export function createNpmPackageManager() {
|
|||
return scanner.shouldScan(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {Promise<{name: string, version: string, type: string}[]>}
|
||||
*/
|
||||
function getDependencyUpdatesForCommand(args) {
|
||||
const scanner = findDependencyScannerForCommand(
|
||||
commandScannerMapping,
|
||||
|
|
@ -32,12 +45,22 @@ export function createNpmPackageManager() {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {Record<string, import("./dependencyScanner/commandArgumentScanner.js").CommandArgumentScanner>}
|
||||
*/
|
||||
const commandScannerMapping = {
|
||||
[npmInstallCommand]: commandArgumentScanner(),
|
||||
[npmUpdateCommand]: commandArgumentScanner(),
|
||||
[npmExecCommand]: commandArgumentScanner({ ignoreDryRun: true }), // exec command doesn't support dry-run
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Record<string, import("./dependencyScanner/commandArgumentScanner.js").CommandArgumentScanner>} scanners
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {import("./dependencyScanner/commandArgumentScanner.js").CommandArgumentScanner}
|
||||
*/
|
||||
function findDependencyScannerForCommand(scanners, args) {
|
||||
const command = getNpmCommandForArgs(args);
|
||||
if (!command) {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,29 @@ import { resolvePackageVersion } from "../../../api/npmApi.js";
|
|||
import { parsePackagesFromInstallArgs } from "../parsing/parsePackagesFromInstallArgs.js";
|
||||
import { hasDryRunArg } from "../utils/npmCommands.js";
|
||||
|
||||
/**
|
||||
* @typedef {Object} ScanResult
|
||||
* @property {string} name
|
||||
* @property {string} version
|
||||
* @property {string} type
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ScannerOptions
|
||||
* @property {boolean} [ignoreDryRun]
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef CommandArgumentScanner
|
||||
* @property {(args: string[]) => Promise<ScanResult[]>} scan
|
||||
* @property {(args: string[]) => boolean} shouldScan
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {ScannerOptions} [opts]
|
||||
*
|
||||
* @returns {CommandArgumentScanner}
|
||||
*/
|
||||
export function commandArgumentScanner(opts) {
|
||||
const ignoreDryRun = opts?.ignoreDryRun ?? false;
|
||||
|
||||
|
|
@ -10,14 +33,28 @@ export function commandArgumentScanner(opts) {
|
|||
shouldScan: (args) => shouldScanDependencies(args, ignoreDryRun),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {Promise<ScanResult[]>}
|
||||
*/
|
||||
function scanDependencies(args) {
|
||||
return checkChangesFromArgs(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @param {boolean} ignoreDryRun
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function shouldScanDependencies(args, ignoreDryRun) {
|
||||
return ignoreDryRun || !hasDryRunArg(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {Promise<ScanResult[]>}
|
||||
*/
|
||||
export async function checkChangesFromArgs(args) {
|
||||
const changes = [];
|
||||
const packageUpdates = parsePackagesFromInstallArgs(args);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
/**
|
||||
* @returns {import("./commandArgumentScanner.js").CommandArgumentScanner}
|
||||
*/
|
||||
export function nullScanner() {
|
||||
return {
|
||||
scan: () => [],
|
||||
scan: async () => [],
|
||||
shouldScan: () => false,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,22 @@
|
|||
/**
|
||||
* @typedef {Object} PackageDetail
|
||||
* @property {string} name
|
||||
* @property {string} version
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} NpmOption
|
||||
* @property {string} name
|
||||
* @property {number} numberOfParameters
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {PackageDetail[]}
|
||||
*/
|
||||
export function parsePackagesFromInstallArgs(args) {
|
||||
const changes = [];
|
||||
/** @type {{name: string, version: string | null}[]} */
|
||||
const changes = [];
|
||||
let defaultTag = "latest";
|
||||
|
||||
// Skip first argument (install command)
|
||||
|
|
@ -32,9 +49,13 @@ export function parsePackagesFromInstallArgs(args) {
|
|||
}
|
||||
}
|
||||
|
||||
return changes;
|
||||
return /** @type {PackageDetail[]} */ (changes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {NpmOption | undefined}
|
||||
*/
|
||||
function getNpmOption(arg) {
|
||||
if (isNpmOptionWithParameter(arg)) {
|
||||
return {
|
||||
|
|
@ -54,6 +75,10 @@ function getNpmOption(arg) {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isNpmOptionWithParameter(arg) {
|
||||
const optionsWithParameters = [
|
||||
"--access",
|
||||
|
|
@ -81,6 +106,10 @@ function isNpmOptionWithParameter(arg) {
|
|||
return optionsWithParameters.includes(arg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {{name: string, version: string | null}}
|
||||
*/
|
||||
function parsePackagename(arg) {
|
||||
arg = removeAlias(arg);
|
||||
const lastAtIndex = arg.lastIndexOf("@");
|
||||
|
|
@ -102,6 +131,10 @@ function parsePackagename(arg) {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {string}
|
||||
*/
|
||||
function removeAlias(arg) {
|
||||
const aliasIndex = arg.indexOf("@npm:");
|
||||
if (aliasIndex !== -1) {
|
||||
|
|
|
|||
|
|
@ -2,14 +2,20 @@ import { ui } from "../../environment/userInteraction.js";
|
|||
import { safeSpawn } from "../../utils/safeSpawn.js";
|
||||
import { mergeSafeChainProxyEnvironmentVariables } from "../../registryProxy/registryProxy.js";
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {Promise<{status: number}>}
|
||||
*/
|
||||
export async function runNpm(args) {
|
||||
try {
|
||||
const result = await safeSpawn("npm", args, {
|
||||
stdio: "inherit",
|
||||
// @ts-expect-error values of process.env can be string | undefined
|
||||
env: mergeSafeChainProxyEnvironmentVariables(process.env),
|
||||
});
|
||||
return { status: result.status };
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
if (error.status) {
|
||||
return { status: error.status };
|
||||
} else {
|
||||
|
|
@ -19,6 +25,10 @@ export async function runNpm(args) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {Promise<{status: number, output?: string}>}
|
||||
*/
|
||||
export async function dryRunNpmCommandAndOutput(args) {
|
||||
try {
|
||||
const result = await safeSpawn(
|
||||
|
|
@ -26,6 +36,7 @@ export async function dryRunNpmCommandAndOutput(args) {
|
|||
[...args, "--ignore-scripts", "--dry-run"],
|
||||
{
|
||||
stdio: "pipe",
|
||||
// @ts-expect-error values of process.env can be string | undefined
|
||||
env: mergeSafeChainProxyEnvironmentVariables(process.env),
|
||||
}
|
||||
);
|
||||
|
|
@ -33,7 +44,7 @@ export async function dryRunNpmCommandAndOutput(args) {
|
|||
status: result.status,
|
||||
output: result.status === 0 ? result.stdout : result.stderr,
|
||||
};
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
if (error.status) {
|
||||
const output =
|
||||
error.stdout?.toString() ??
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
// This was ran with the abbrev package to generate the abbrevs object below
|
||||
// console.log(abbrev(commands.concat(Object.keys(aliases))));
|
||||
/** @type {Record<string, string>} */
|
||||
export const abbrevs = {
|
||||
ac: "access",
|
||||
acc: "access",
|
||||
|
|
|
|||
|
|
@ -73,6 +73,7 @@ const commands = [
|
|||
];
|
||||
|
||||
// These must resolve to an entry in commands
|
||||
/** @type {Record<string, string>} */
|
||||
const aliases = {
|
||||
// aliases
|
||||
author: "owner",
|
||||
|
|
@ -138,6 +139,10 @@ const aliases = {
|
|||
"add-user": "adduser",
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {string} c
|
||||
* @returns {string | undefined}
|
||||
*/
|
||||
export function deref(c) {
|
||||
if (!c) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
import { deref } from "./cmd-list.js";
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export function getNpmCommandForArgs(args) {
|
||||
if (args.length === 0) {
|
||||
return null;
|
||||
|
|
@ -13,6 +17,10 @@ export function getNpmCommandForArgs(args) {
|
|||
return argCommand;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function hasDryRunArg(args) {
|
||||
return args.some((arg) => arg === "--dry-run");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import { commandArgumentScanner } from "./dependencyScanner/commandArgumentScanner.js";
|
||||
import { runNpx } from "./runNpxCommand.js";
|
||||
|
||||
/**
|
||||
* @returns {import("../currentPackageManager.js").PackageManager}
|
||||
*/
|
||||
export function createNpxPackageManager() {
|
||||
const scanner = commandArgumentScanner();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,16 +1,28 @@
|
|||
import { resolvePackageVersion } from "../../../api/npmApi.js";
|
||||
import { parsePackagesFromArguments } from "../parsing/parsePackagesFromArguments.js";
|
||||
|
||||
/**
|
||||
* @returns {import("../../npm/dependencyScanner/commandArgumentScanner.js").CommandArgumentScanner}
|
||||
*/
|
||||
export function commandArgumentScanner() {
|
||||
return {
|
||||
scan: (args) => scanDependencies(args),
|
||||
shouldScan: () => true, // all npx commands need to be scanned, npx doesn't have dry-run
|
||||
shouldScan: (args) => true, // all npx commands need to be scanned, npx doesn't have dry-run
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {Promise<import("../../npm/dependencyScanner/commandArgumentScanner.js").ScanResult[]>}
|
||||
*/
|
||||
function scanDependencies(args) {
|
||||
return checkChangesFromArgs(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {Promise<import("../../npm/dependencyScanner/commandArgumentScanner.js").ScanResult[]>}
|
||||
*/
|
||||
export async function checkChangesFromArgs(args) {
|
||||
const changes = [];
|
||||
const packageUpdates = parsePackagesFromArguments(args);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {{name: string, version: string}[]}
|
||||
*/
|
||||
export function parsePackagesFromArguments(args) {
|
||||
let defaultTag = "latest";
|
||||
|
||||
|
|
@ -21,6 +26,10 @@ export function parsePackagesFromArguments(args) {
|
|||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {{name: string, numberOfParameters: number} | undefined}
|
||||
*/
|
||||
function getOption(arg) {
|
||||
if (isOptionWithParameter(arg)) {
|
||||
return {
|
||||
|
|
@ -41,6 +50,10 @@ function getOption(arg) {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isOptionWithParameter(arg) {
|
||||
const optionsWithParameters = [
|
||||
"--access",
|
||||
|
|
@ -68,6 +81,11 @@ function isOptionWithParameter(arg) {
|
|||
return optionsWithParameters.includes(arg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @param {string} defaultTag
|
||||
* @returns {{name: string, version: string}}
|
||||
*/
|
||||
function parsePackagename(arg, defaultTag) {
|
||||
// format can be --package=name@version
|
||||
// in that case, we need to remove the --package= part
|
||||
|
|
@ -97,6 +115,10 @@ function parsePackagename(arg, defaultTag) {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {string}
|
||||
*/
|
||||
function removeAlias(arg) {
|
||||
// removes the alias.
|
||||
// Eg.: server@npm:http-server@latest becomes http-server@latest
|
||||
|
|
|
|||
|
|
@ -2,14 +2,20 @@ import { ui } from "../../environment/userInteraction.js";
|
|||
import { safeSpawn } from "../../utils/safeSpawn.js";
|
||||
import { mergeSafeChainProxyEnvironmentVariables } from "../../registryProxy/registryProxy.js";
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {Promise<{status: number}>}
|
||||
*/
|
||||
export async function runNpx(args) {
|
||||
try {
|
||||
const result = await safeSpawn("npx", args, {
|
||||
stdio: "inherit",
|
||||
// @ts-expect-error values of process.env can be string | undefined
|
||||
env: mergeSafeChainProxyEnvironmentVariables(process.env),
|
||||
});
|
||||
return { status: result.status };
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
if (error.status) {
|
||||
return { status: error.status };
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,9 @@ import { runPnpmCommand } from "./runPnpmCommand.js";
|
|||
|
||||
const scanner = commandArgumentScanner();
|
||||
|
||||
/**
|
||||
* @returns {import("../currentPackageManager.js").PackageManager}
|
||||
*/
|
||||
export function createPnpmPackageManager() {
|
||||
return {
|
||||
runCommand: (args) => runPnpmCommand(args, "pnpm"),
|
||||
|
|
@ -23,6 +26,9 @@ export function createPnpmPackageManager() {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {import("../currentPackageManager.js").PackageManager}
|
||||
*/
|
||||
export function createPnpxPackageManager() {
|
||||
return {
|
||||
runCommand: (args) => runPnpmCommand(args, "pnpx"),
|
||||
|
|
@ -32,6 +38,11 @@ export function createPnpxPackageManager() {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @param {boolean} isPnpx
|
||||
* @returns {Promise<import("../npm/dependencyScanner/commandArgumentScanner.js").ScanResult[]>}
|
||||
*/
|
||||
function getDependencyUpdatesForCommand(args, isPnpx) {
|
||||
if (isPnpx) {
|
||||
return scanner.scan(args);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import { resolvePackageVersion } from "../../../api/npmApi.js";
|
||||
import { parsePackagesFromArguments } from "../parsing/parsePackagesFromArguments.js";
|
||||
|
||||
/**
|
||||
* @returns {import("../../npm/dependencyScanner/commandArgumentScanner.js").CommandArgumentScanner}
|
||||
*/
|
||||
export function commandArgumentScanner() {
|
||||
return {
|
||||
scan: (args) => scanDependencies(args),
|
||||
|
|
@ -8,6 +11,10 @@ export function commandArgumentScanner() {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {Promise<import("../../npm/dependencyScanner/commandArgumentScanner.js").ScanResult[]>}
|
||||
*/
|
||||
async function scanDependencies(args) {
|
||||
const changes = [];
|
||||
const packageUpdates = parsePackagesFromArguments(args);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {{name: string, version: string}[]}
|
||||
*/
|
||||
export function parsePackagesFromArguments(args) {
|
||||
const changes = [];
|
||||
let defaultTag = "latest";
|
||||
|
|
@ -22,6 +26,10 @@ export function parsePackagesFromArguments(args) {
|
|||
return changes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {{name: string, numberOfParameters: number} | undefined}
|
||||
*/
|
||||
function getOption(arg) {
|
||||
if (isOptionWithParameter(arg)) {
|
||||
return {
|
||||
|
|
@ -42,12 +50,21 @@ function getOption(arg) {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isOptionWithParameter(arg) {
|
||||
const optionsWithParameters = ["--C", "--dir"];
|
||||
|
||||
return optionsWithParameters.includes(arg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @param {string} defaultTag
|
||||
* @returns {{name: string, version: string}}
|
||||
*/
|
||||
function parsePackagename(arg, defaultTag) {
|
||||
// format can be --package=name@version
|
||||
// in that case, we need to remove the --package= part
|
||||
|
|
@ -77,6 +94,10 @@ function parsePackagename(arg, defaultTag) {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {string}
|
||||
*/
|
||||
function removeAlias(arg) {
|
||||
// removes the alias.
|
||||
// Eg.: server@npm:http-server@latest becomes http-server@latest
|
||||
|
|
|
|||
|
|
@ -2,17 +2,24 @@ import { ui } from "../../environment/userInteraction.js";
|
|||
import { mergeSafeChainProxyEnvironmentVariables } from "../../registryProxy/registryProxy.js";
|
||||
import { safeSpawn } from "../../utils/safeSpawn.js";
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @param {string} [toolName]
|
||||
* @returns {Promise<{status: number}>}
|
||||
*/
|
||||
export async function runPnpmCommand(args, toolName = "pnpm") {
|
||||
try {
|
||||
let result;
|
||||
if (toolName === "pnpm") {
|
||||
result = await safeSpawn("pnpm", args, {
|
||||
stdio: "inherit",
|
||||
// @ts-expect-error values of process.env can be string | undefined
|
||||
env: mergeSafeChainProxyEnvironmentVariables(process.env),
|
||||
});
|
||||
} else if (toolName === "pnpx") {
|
||||
result = await safeSpawn("pnpx", args, {
|
||||
stdio: "inherit",
|
||||
// @ts-expect-error values of process.env can be string | undefined
|
||||
env: mergeSafeChainProxyEnvironmentVariables(process.env),
|
||||
});
|
||||
} else {
|
||||
|
|
@ -20,7 +27,7 @@ export async function runPnpmCommand(args, toolName = "pnpm") {
|
|||
}
|
||||
|
||||
return { status: result.status };
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
if (error.status) {
|
||||
return { status: error.status };
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,9 @@ import { runYarnCommand } from "./runYarnCommand.js";
|
|||
|
||||
const scanner = commandArgumentScanner();
|
||||
|
||||
/**
|
||||
* @returns {import("../currentPackageManager.js").PackageManager}
|
||||
*/
|
||||
export function createYarnPackageManager() {
|
||||
return {
|
||||
runCommand: runYarnCommand,
|
||||
|
|
@ -18,6 +21,11 @@ export function createYarnPackageManager() {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @param {...string} commandArgs
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function matchesCommand(args, ...commandArgs) {
|
||||
if (args.length < commandArgs.length) {
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import { resolvePackageVersion } from "../../../api/npmApi.js";
|
||||
import { parsePackagesFromArguments } from "../parsing/parsePackagesFromArguments.js";
|
||||
|
||||
/**
|
||||
* @returns {import("../../npm/dependencyScanner/commandArgumentScanner.js").CommandArgumentScanner}
|
||||
*/
|
||||
export function commandArgumentScanner() {
|
||||
return {
|
||||
scan: (args) => scanDependencies(args),
|
||||
|
|
@ -8,6 +11,10 @@ export function commandArgumentScanner() {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {Promise<import("../../npm/dependencyScanner/commandArgumentScanner.js").ScanResult[]>}
|
||||
*/
|
||||
async function scanDependencies(args) {
|
||||
const changes = [];
|
||||
const packageUpdates = parsePackagesFromArguments(args);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
/**
|
||||
* @param {string[]} args
|
||||
* @returns {{name: string, version: string}[]}
|
||||
*/
|
||||
export function parsePackagesFromArguments(args) {
|
||||
const changes = [];
|
||||
let defaultTag = "latest";
|
||||
|
|
@ -22,6 +26,11 @@ export function parsePackagesFromArguments(args) {
|
|||
return changes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
*
|
||||
* @returns {{name: string, numberOfParameters: number} | undefined}
|
||||
*/
|
||||
function getOption(arg) {
|
||||
if (isOptionWithParameter(arg)) {
|
||||
return {
|
||||
|
|
@ -42,6 +51,11 @@ function getOption(arg) {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isOptionWithParameter(arg) {
|
||||
const optionsWithParameters = [
|
||||
"--use-yarnrc",
|
||||
|
|
@ -64,6 +78,12 @@ function isOptionWithParameter(arg) {
|
|||
return optionsWithParameters.includes(arg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @param {string} defaultTag
|
||||
*
|
||||
* @returns {{name: string, version: string}}
|
||||
*/
|
||||
function parsePackagename(arg, defaultTag) {
|
||||
// format can be --package=name@version
|
||||
// in that case, we need to remove the --package= part
|
||||
|
|
@ -93,6 +113,10 @@ function parsePackagename(arg, defaultTag) {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
* @returns {string}
|
||||
*/
|
||||
function removeAlias(arg) {
|
||||
// removes the alias.
|
||||
// Eg.: server@npm:http-server@latest becomes http-server@latest
|
||||
|
|
|
|||
|
|
@ -2,8 +2,14 @@ import { ui } from "../../environment/userInteraction.js";
|
|||
import { safeSpawn } from "../../utils/safeSpawn.js";
|
||||
import { mergeSafeChainProxyEnvironmentVariables } from "../../registryProxy/registryProxy.js";
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {Promise<{status: number}>}
|
||||
*/
|
||||
export async function runYarnCommand(args) {
|
||||
try {
|
||||
// @ts-expect-error values of process.env can be string | undefined
|
||||
const env = mergeSafeChainProxyEnvironmentVariables(process.env);
|
||||
await fixYarnProxyEnvironmentVariables(env);
|
||||
|
||||
|
|
@ -12,7 +18,7 @@ export async function runYarnCommand(args) {
|
|||
env,
|
||||
});
|
||||
return { status: result.status };
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
if (error.status) {
|
||||
return { status: error.status };
|
||||
} else {
|
||||
|
|
@ -22,6 +28,11 @@ export async function runYarnCommand(args) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Record<string, string>} env
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function fixYarnProxyEnvironmentVariables(env) {
|
||||
// Yarn ignores standard proxy environment variable HTTPS_PROXY
|
||||
// It does respect NODE_EXTRA_CA_CERTS for custom CA certificates though.
|
||||
|
|
|
|||
|
|
@ -12,6 +12,10 @@ export function getCaCertPath() {
|
|||
return path.join(certFolder, "ca-cert.pem");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} hostname
|
||||
* @returns {{privateKey: string, certificate: string}}
|
||||
*/
|
||||
export function generateCertForHost(hostname) {
|
||||
let existingCert = certCache.get(hostname);
|
||||
if (existingCert) {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,11 @@ import { generateCertForHost } from "./certUtils.js";
|
|||
import { HttpsProxyAgent } from "https-proxy-agent";
|
||||
import { ui } from "../environment/userInteraction.js";
|
||||
|
||||
/**
|
||||
* @param {import("http").IncomingMessage} req
|
||||
* @param {import("net").Socket} clientSocket
|
||||
* @param {(target: string) => Promise<boolean>} isAllowed
|
||||
*/
|
||||
export function mitmConnect(req, clientSocket, isAllowed) {
|
||||
const { hostname } = new URL(`http://${req.url}`);
|
||||
|
||||
|
|
@ -16,6 +21,7 @@ export function mitmConnect(req, clientSocket, isAllowed) {
|
|||
|
||||
server.on("error", (err) => {
|
||||
ui.writeError(`Safe-chain: HTTPS server error: ${err.message}`);
|
||||
// @ts-expect-error Property 'headersSent' does not exist on type 'Socket'
|
||||
if (!clientSocket.headersSent) {
|
||||
clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n");
|
||||
} else if (clientSocket.writable) {
|
||||
|
|
@ -30,10 +36,22 @@ export function mitmConnect(req, clientSocket, isAllowed) {
|
|||
server.emit("connection", clientSocket);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} hostname
|
||||
* @param {(target: string) => Promise<boolean>} isAllowed
|
||||
* @returns {import("https").Server}
|
||||
*/
|
||||
function createHttpsServer(hostname, isAllowed) {
|
||||
const cert = generateCertForHost(hostname);
|
||||
|
||||
/**
|
||||
* @param {import("http").IncomingMessage} req
|
||||
* @param {import("http").ServerResponse} res
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function handleRequest(req, res) {
|
||||
// @ts-expect-error req.url might be undefined
|
||||
const pathAndQuery = getRequestPathAndQuery(req.url);
|
||||
const targetUrl = `https://${hostname}${pathAndQuery}`;
|
||||
|
||||
|
|
@ -58,6 +76,10 @@ function createHttpsServer(hostname, isAllowed) {
|
|||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @returns {*|string}
|
||||
*/
|
||||
function getRequestPathAndQuery(url) {
|
||||
if (url.startsWith("http://") || url.startsWith("https://")) {
|
||||
const parsedUrl = new URL(url);
|
||||
|
|
@ -66,6 +88,11 @@ function getRequestPathAndQuery(url) {
|
|||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("http").IncomingMessage} req
|
||||
* @param {string} hostname
|
||||
* @param {import("http").ServerResponse} res
|
||||
*/
|
||||
function forwardRequest(req, hostname, res) {
|
||||
const proxyReq = createProxyRequest(hostname, req, res);
|
||||
|
||||
|
|
@ -88,7 +115,15 @@ function forwardRequest(req, hostname, res) {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} hostname
|
||||
* @param {import("http").IncomingMessage} req
|
||||
* @param {import("http").ServerResponse} res
|
||||
*
|
||||
* @returns {import("http").ClientRequest}
|
||||
*/
|
||||
function createProxyRequest(hostname, req, res) {
|
||||
/** @type {import("http").RequestOptions} */
|
||||
const options = {
|
||||
hostname: hostname,
|
||||
port: 443,
|
||||
|
|
@ -97,7 +132,9 @@ function createProxyRequest(hostname, req, res) {
|
|||
headers: { ...req.headers },
|
||||
};
|
||||
|
||||
delete options.headers.host;
|
||||
if (options.headers && "host" in options.headers) {
|
||||
delete options.headers["host"];
|
||||
}
|
||||
|
||||
const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;
|
||||
if (httpsProxy) {
|
||||
|
|
@ -115,6 +152,7 @@ function createProxyRequest(hostname, req, res) {
|
|||
}
|
||||
});
|
||||
|
||||
// @ts-expect-error statusCode might be undefined
|
||||
res.writeHead(proxyRes.statusCode, proxyRes.headers);
|
||||
proxyRes.pipe(res);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
export const knownRegistries = ["registry.npmjs.org", "registry.yarnpkg.com"];
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @returns {{packageName: string | undefined, version: string | undefined}}
|
||||
*/
|
||||
export function parsePackageFromUrl(url) {
|
||||
let packageName, version, registry;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,14 @@
|
|||
import * as http from "http";
|
||||
import * as https from "https";
|
||||
|
||||
/**
|
||||
* @param {import("http").IncomingMessage} req
|
||||
* @param {import("http").ServerResponse} res
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
export function handleHttpProxyRequest(req, res) {
|
||||
// @ts-expect-error req.url might be undefined
|
||||
const url = new URL(req.url);
|
||||
|
||||
// The protocol for the plainHttpProxy should usually only be http:
|
||||
|
|
@ -20,9 +27,11 @@ export function handleHttpProxyRequest(req, res) {
|
|||
|
||||
const proxyRequest = protocol
|
||||
.request(
|
||||
// @ts-expect-error req.url might be undefined
|
||||
req.url,
|
||||
{ method: req.method, headers: req.headers },
|
||||
(proxyRes) => {
|
||||
// @ts-expect-error statusCode might be undefined
|
||||
res.writeHead(proxyRes.statusCode, proxyRes.headers);
|
||||
proxyRes.pipe(res);
|
||||
|
||||
|
|
|
|||
|
|
@ -9,6 +9,9 @@ import { ui } from "../environment/userInteraction.js";
|
|||
import chalk from "chalk";
|
||||
|
||||
const SERVER_STOP_TIMEOUT_MS = 1000;
|
||||
/**
|
||||
* @type {{port: number | null, blockedRequests: {packageName: string, version: string, url: string}[]}}
|
||||
*/
|
||||
const state = {
|
||||
port: null,
|
||||
blockedRequests: [],
|
||||
|
|
@ -24,6 +27,9 @@ export function createSafeChainProxy() {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Record<string, string>}
|
||||
*/
|
||||
function getSafeChainProxyEnvironmentVariables() {
|
||||
if (!state.port) {
|
||||
return {};
|
||||
|
|
@ -36,6 +42,11 @@ function getSafeChainProxyEnvironmentVariables() {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Record<string, string>} env
|
||||
*
|
||||
* @returns {Record<string, string>}
|
||||
*/
|
||||
export function mergeSafeChainProxyEnvironmentVariables(env) {
|
||||
const proxyEnv = getSafeChainProxyEnvironmentVariables();
|
||||
|
||||
|
|
@ -67,6 +78,11 @@ function createProxyServer() {
|
|||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("http").Server} server
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
function startServer(server) {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Passing port 0 makes the OS assign an available port
|
||||
|
|
@ -86,6 +102,11 @@ function startServer(server) {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("http").Server} server
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
function stopServer(server) {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
|
|
@ -99,10 +120,18 @@ function stopServer(server) {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("http").IncomingMessage} req
|
||||
* @param {import("net").Socket} clientSocket
|
||||
* @param {Buffer} head
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function handleConnect(req, clientSocket, head) {
|
||||
// CONNECT method is used for HTTPS requests
|
||||
// It establishes a tunnel to the server identified by the request URL
|
||||
|
||||
// @ts-expect-error req.url might be undefined
|
||||
if (knownRegistries.some((reg) => req.url.includes(reg))) {
|
||||
// For npm and yarn registries, we want to intercept and inspect the traffic
|
||||
// so we can block packages with malware
|
||||
|
|
@ -113,6 +142,10 @@ function handleConnect(req, clientSocket, head) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async function isAllowedUrl(url) {
|
||||
const { packageName, version } = parsePackageFromUrl(url);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,13 @@
|
|||
import * as net from "net";
|
||||
import { ui } from "../environment/userInteraction.js";
|
||||
|
||||
/**
|
||||
* @param {import("http").IncomingMessage} req
|
||||
* @param {import("net").Socket} clientSocket
|
||||
* @param {Buffer} head
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
export function tunnelRequest(req, clientSocket, head) {
|
||||
const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;
|
||||
|
||||
|
|
@ -21,9 +28,17 @@ export function tunnelRequest(req, clientSocket, head) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("http").IncomingMessage} req
|
||||
* @param {import("net").Socket} clientSocket
|
||||
* @param {Buffer} head
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function tunnelRequestToDestination(req, clientSocket, head) {
|
||||
const { port, hostname } = new URL(`http://${req.url}`);
|
||||
|
||||
// @ts-expect-error port from URL is a string but net.connect accepts number
|
||||
const serverSocket = net.connect(port || 443, hostname, () => {
|
||||
clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
|
||||
serverSocket.write(head);
|
||||
|
|
@ -49,11 +64,18 @@ function tunnelRequestToDestination(req, clientSocket, head) {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("http").IncomingMessage} req
|
||||
* @param {import("net").Socket} clientSocket
|
||||
* @param {Buffer} head
|
||||
* @param {string} proxyUrl
|
||||
*/
|
||||
function tunnelRequestViaProxy(req, clientSocket, head, proxyUrl) {
|
||||
const { port, hostname } = new URL(`http://${req.url}`);
|
||||
const proxy = new URL(proxyUrl);
|
||||
|
||||
// Connect to proxy server
|
||||
// @ts-expect-error net.connect wants port as number but proxy.port is string
|
||||
const proxySocket = net.connect({
|
||||
host: proxy.hostname,
|
||||
port: proxy.port,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,25 @@ import {
|
|||
openMalwareDatabase,
|
||||
} from "../malwareDatabase.js";
|
||||
|
||||
/**
|
||||
* @typedef PackageChange
|
||||
* @property {string} name
|
||||
* @property {string} version
|
||||
* @property {string} type
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef AuditResult
|
||||
* @property {PackageChange[]} allowedChanges
|
||||
* @property {(PackageChange & {reason: string})[]} disallowedChanges
|
||||
* @property {boolean} isAllowed
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {PackageChange[]} changes
|
||||
*
|
||||
* @returns {Promise<AuditResult>}
|
||||
*/
|
||||
export async function auditChanges(changes) {
|
||||
const allowedChanges = [];
|
||||
const disallowedChanges = [];
|
||||
|
|
@ -34,6 +53,10 @@ export async function auditChanges(changes) {
|
|||
return auditResults;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{name: string, version: string, type: string}[]} changes
|
||||
* @returns {Promise<{name: string, version: string, status: string}[]>}
|
||||
*/
|
||||
async function getPackagesWithMalware(changes) {
|
||||
if (changes.length === 0) {
|
||||
return [];
|
||||
|
|
|
|||
|
|
@ -5,6 +5,11 @@ import chalk from "chalk";
|
|||
import { getPackageManager } from "../packagemanager/currentPackageManager.js";
|
||||
import { ui } from "../environment/userInteraction.js";
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function shouldScanCommand(args) {
|
||||
if (!args || args.length === 0) {
|
||||
return false;
|
||||
|
|
@ -13,6 +18,11 @@ export function shouldScanCommand(args) {
|
|||
return getPackageManager().isSupportedCommand(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {Promise<number | never[]>}
|
||||
*/
|
||||
export async function scanCommand(args) {
|
||||
if (!shouldScanCommand(args)) {
|
||||
return [];
|
||||
|
|
@ -23,6 +33,7 @@ export async function scanCommand(args) {
|
|||
const spinner = ui.startProcess(
|
||||
"Safe-chain: Scanning for malicious packages..."
|
||||
);
|
||||
/** @type {import("./audit/index.js").AuditResult | undefined} */
|
||||
let audit;
|
||||
|
||||
await Promise.race([
|
||||
|
|
@ -44,7 +55,7 @@ export async function scanCommand(args) {
|
|||
}
|
||||
|
||||
audit = await auditChanges(changes);
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
spinner.fail(`Safe-chain: Error while scanning.`);
|
||||
throw error;
|
||||
}
|
||||
|
|
@ -69,6 +80,12 @@ export async function scanCommand(args) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("./audit/index.js").PackageChange[]} changes
|
||||
* @param spinner {import("../environment/userInteraction.js").Spinner}
|
||||
*
|
||||
* @return {void}
|
||||
*/
|
||||
function printMaliciousChanges(changes, spinner) {
|
||||
spinner.fail("Safe-chain: " + chalk.bold("Malicious changes detected:"));
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,13 @@ import {
|
|||
} from "../config/configFile.js";
|
||||
import { ui } from "../environment/userInteraction.js";
|
||||
|
||||
/**
|
||||
* @typedef MalwareDatabase
|
||||
* @property {function(string, string): string} getPackageStatus
|
||||
* @property {function(string, string): boolean} isMalware
|
||||
*/
|
||||
|
||||
/** @type {MalwareDatabase | null} */
|
||||
let cachedMalwareDatabase = null;
|
||||
|
||||
export async function openMalwareDatabase() {
|
||||
|
|
@ -17,6 +24,11 @@ export async function openMalwareDatabase() {
|
|||
|
||||
const malwareDatabase = await getMalwareDatabase();
|
||||
|
||||
/**
|
||||
* @param {string} name
|
||||
* @param {string} version
|
||||
* @returns {string}
|
||||
*/
|
||||
function getPackageStatus(name, version) {
|
||||
const packageData = malwareDatabase.find(
|
||||
(pkg) =>
|
||||
|
|
@ -31,7 +43,7 @@ export async function openMalwareDatabase() {
|
|||
return packageData.reason;
|
||||
}
|
||||
|
||||
// This implicitely caches the malware database
|
||||
// This implicitly caches the malware database
|
||||
// that's closed over by the getPackageStatus function
|
||||
cachedMalwareDatabase = {
|
||||
getPackageStatus,
|
||||
|
|
@ -43,6 +55,9 @@ export async function openMalwareDatabase() {
|
|||
return cachedMalwareDatabase;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<import("../api/aikido.js").MalwarePackage[]>}
|
||||
*/
|
||||
async function getMalwareDatabase() {
|
||||
const { malwareDatabase: cachedDatabase, version: cachedVersion } =
|
||||
readDatabaseFromLocalCache();
|
||||
|
|
@ -56,10 +71,11 @@ async function getMalwareDatabase() {
|
|||
}
|
||||
|
||||
const { malwareDatabase, version } = await fetchMalwareDatabase();
|
||||
// @ts-expect-error version can be undefined
|
||||
writeDatabaseToLocalCache(malwareDatabase, version);
|
||||
|
||||
return malwareDatabase;
|
||||
} catch (error) {
|
||||
} catch (/** @type any */ error) {
|
||||
if (cachedDatabase) {
|
||||
ui.writeWarning(
|
||||
"Failed to fetch the latest malware database. Using cached version."
|
||||
|
|
@ -70,6 +86,11 @@ async function getMalwareDatabase() {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} status
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isMalwareStatus(status) {
|
||||
let malwareStatus = status.toUpperCase();
|
||||
return malwareStatus === MALWARE_STATUS_MALWARE;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,15 @@ import * as os from "os";
|
|||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
/**
|
||||
* @typedef AikidoTool
|
||||
* @property {string} tool
|
||||
* @property {string} aikidoCommand
|
||||
*/
|
||||
|
||||
/**
|
||||
* @type {AikidoTool[]}
|
||||
*/
|
||||
export const knownAikidoTools = [
|
||||
{ tool: "npm", aikidoCommand: "aikido-npm" },
|
||||
{ tool: "npx", aikidoCommand: "aikido-npx" },
|
||||
|
|
@ -30,6 +39,11 @@ export function getPackageManagerList() {
|
|||
return `${tools.join(", ")}, and ${lastTool} commands`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} executableName
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function doesExecutableExistOnSystem(executableName) {
|
||||
if (os.platform() === "win32") {
|
||||
const result = spawnSync("where", [executableName], { stdio: "ignore" });
|
||||
|
|
@ -40,6 +54,13 @@ export function doesExecutableExistOnSystem(executableName) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} filePath
|
||||
* @param {RegExp} pattern
|
||||
* @param {string} [eol]
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
export function removeLinesMatchingPattern(filePath, pattern, eol) {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return;
|
||||
|
|
@ -54,6 +75,12 @@ export function removeLinesMatchingPattern(filePath, pattern, eol) {
|
|||
}
|
||||
|
||||
const maxLineLength = 100;
|
||||
|
||||
/**
|
||||
* @param {string} line
|
||||
* @param {RegExp} pattern
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function shouldRemoveLine(line, pattern) {
|
||||
const isPatternMatch = pattern.test(line);
|
||||
|
||||
|
|
@ -82,7 +109,14 @@ function shouldRemoveLine(line, pattern) {
|
|||
return true;
|
||||
}
|
||||
|
||||
export function addLineToFile(filePath, line, eol) {
|
||||
/**
|
||||
* @param {string} filePath
|
||||
* @param {string} line
|
||||
* @param {string} [eol]
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
export function addLineToFile(filePath, line, eol ) {
|
||||
createFileIfNotExists(filePath);
|
||||
|
||||
eol = eol || os.EOL;
|
||||
|
|
@ -92,6 +126,11 @@ export function addLineToFile(filePath, line, eol) {
|
|||
fs.writeFileSync(filePath, updatedContent, "utf-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} filePath
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function createFileIfNotExists(filePath) {
|
||||
if (fs.existsSync(filePath)) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -28,6 +28,11 @@ export async function setupCi() {
|
|||
ui.writeInformation(`Added shims directory to PATH for CI environments.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} shimsDir
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function createUnixShims(shimsDir) {
|
||||
// Read the template file
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
|
|
@ -64,6 +69,11 @@ function createUnixShims(shimsDir) {
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} shimsDir
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function createWindowsShims(shimsDir) {
|
||||
// Read the template file
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
|
|
@ -97,6 +107,11 @@ function createWindowsShims(shimsDir) {
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} shimsDir
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function createShims(shimsDir) {
|
||||
if (os.platform() === "win32") {
|
||||
createWindowsShims(shimsDir);
|
||||
|
|
@ -105,6 +120,11 @@ function createShims(shimsDir) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} shimsDir
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function modifyPathForCi(shimsDir) {
|
||||
if (process.env.GITHUB_PATH) {
|
||||
// In GitHub Actions, append the shims directory to GITHUB_PATH
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ export async function setup() {
|
|||
ui.emptyLine();
|
||||
ui.writeInformation(`Please restart your terminal to apply the changes.`);
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (/** @type {any} */ error) {
|
||||
ui.writeError(
|
||||
`Failed to set up shell aliases: ${error.message}. Please check your shell configuration.`
|
||||
);
|
||||
|
|
@ -53,6 +53,7 @@ export async function setup() {
|
|||
|
||||
/**
|
||||
* Calls the setup function for the given shell and reports the result.
|
||||
* @param {import("./shellDetection.js").Shell} shell
|
||||
*/
|
||||
function setupShell(shell) {
|
||||
let success = false;
|
||||
|
|
@ -60,7 +61,7 @@ function setupShell(shell) {
|
|||
try {
|
||||
shell.teardown(knownAikidoTools); // First, tear down to prevent duplicate aliases
|
||||
success = shell.setup(knownAikidoTools);
|
||||
} catch (err) {
|
||||
} catch (/** @type {any} */ err) {
|
||||
success = false;
|
||||
error = err;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,17 @@ import windowsPowershell from "./supported-shells/windowsPowershell.js";
|
|||
import fish from "./supported-shells/fish.js";
|
||||
import { ui } from "../environment/userInteraction.js";
|
||||
|
||||
/**
|
||||
* @typedef Shell
|
||||
* @property {string} name
|
||||
* @property {() => boolean} isInstalled
|
||||
* @property {(tools: import("./helpers.js").AikidoTool[]) => boolean} setup
|
||||
* @property {(tools: import("./helpers.js").AikidoTool[]) => boolean} teardown
|
||||
*/
|
||||
|
||||
/**
|
||||
* @returns {Shell[]}
|
||||
*/
|
||||
export function detectShells() {
|
||||
let possibleShells = [zsh, bash, powershell, windowsPowershell, fish];
|
||||
let availableShells = [];
|
||||
|
|
@ -15,7 +26,7 @@ export function detectShells() {
|
|||
availableShells.push(shell);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (/** @type {any} */ error) {
|
||||
ui.writeError(
|
||||
`We were not able to detect which shells are installed on your system. Please check your shell configuration. Error: ${error.message}`
|
||||
);
|
||||
|
|
|
|||
|
|
@ -15,6 +15,11 @@ function isInstalled() {
|
|||
return doesExecutableExistOnSystem(executableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("../helpers.js").AikidoTool[]} tools
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function teardown(tools) {
|
||||
const startupFile = getStartupFile();
|
||||
|
||||
|
|
@ -57,13 +62,18 @@ function getStartupFile() {
|
|||
}).trim();
|
||||
|
||||
return windowsFixPath(path);
|
||||
} catch (error) {
|
||||
} catch (/** @type {any} */ error) {
|
||||
throw new Error(
|
||||
`Command failed: ${startupFileCommand}. Error: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function windowsFixPath(path) {
|
||||
try {
|
||||
if (os.platform() !== "win32") {
|
||||
|
|
@ -93,6 +103,11 @@ function hasCygpath() {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function cygpathw(path) {
|
||||
try {
|
||||
var result = spawnSync("cygpath", ["-w", path], {
|
||||
|
|
@ -108,6 +123,9 @@ function cygpathw(path) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {import("../shellDetection.js").Shell}
|
||||
*/
|
||||
export default {
|
||||
name: shellName,
|
||||
isInstalled,
|
||||
|
|
|
|||
|
|
@ -14,6 +14,11 @@ function isInstalled() {
|
|||
return doesExecutableExistOnSystem(executableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("../helpers.js").AikidoTool[]} tools
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function teardown(tools) {
|
||||
const startupFile = getStartupFile();
|
||||
|
||||
|
|
@ -54,13 +59,16 @@ function getStartupFile() {
|
|||
encoding: "utf8",
|
||||
shell: executableName,
|
||||
}).trim();
|
||||
} catch (error) {
|
||||
} catch (/** @type {any} */ error) {
|
||||
throw new Error(
|
||||
`Command failed: ${startupFileCommand}. Error: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {import("../shellDetection.js").Shell}
|
||||
*/
|
||||
export default {
|
||||
name: shellName,
|
||||
isInstalled,
|
||||
|
|
|
|||
|
|
@ -13,6 +13,11 @@ function isInstalled() {
|
|||
return doesExecutableExistOnSystem(executableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("../helpers.js").AikidoTool[]} tools
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function teardown(tools) {
|
||||
const startupFile = getStartupFile();
|
||||
|
||||
|
|
@ -50,13 +55,16 @@ function getStartupFile() {
|
|||
encoding: "utf8",
|
||||
shell: executableName,
|
||||
}).trim();
|
||||
} catch (error) {
|
||||
} catch (/** @type {any} */ error) {
|
||||
throw new Error(
|
||||
`Command failed: ${startupFileCommand}. Error: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {import("../shellDetection.js").Shell}
|
||||
*/
|
||||
export default {
|
||||
name: shellName,
|
||||
isInstalled,
|
||||
|
|
|
|||
|
|
@ -13,6 +13,11 @@ function isInstalled() {
|
|||
return doesExecutableExistOnSystem(executableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("../helpers.js").AikidoTool[]} tools
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function teardown(tools) {
|
||||
const startupFile = getStartupFile();
|
||||
|
||||
|
|
@ -50,13 +55,16 @@ function getStartupFile() {
|
|||
encoding: "utf8",
|
||||
shell: executableName,
|
||||
}).trim();
|
||||
} catch (error) {
|
||||
} catch (/** @type {any} */ error) {
|
||||
throw new Error(
|
||||
`Command failed: ${startupFileCommand}. Error: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {import("../shellDetection.js").Shell}
|
||||
*/
|
||||
export default {
|
||||
name: shellName,
|
||||
isInstalled,
|
||||
|
|
|
|||
|
|
@ -14,6 +14,11 @@ function isInstalled() {
|
|||
return doesExecutableExistOnSystem(executableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("../helpers.js").AikidoTool[]} tools
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function teardown(tools) {
|
||||
const startupFile = getStartupFile();
|
||||
|
||||
|
|
@ -54,7 +59,7 @@ function getStartupFile() {
|
|||
encoding: "utf8",
|
||||
shell: executableName,
|
||||
}).trim();
|
||||
} catch (error) {
|
||||
} catch (/** @type {any} */ error) {
|
||||
throw new Error(
|
||||
`Command failed: ${startupFileCommand}. Error: ${error.message}`
|
||||
);
|
||||
|
|
|
|||
|
|
@ -3,6 +3,9 @@ import { ui } from "../environment/userInteraction.js";
|
|||
import { detectShells } from "./shellDetection.js";
|
||||
import { knownAikidoTools, getPackageManagerList } from "./helpers.js";
|
||||
|
||||
/**
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function teardown() {
|
||||
ui.writeInformation(
|
||||
chalk.bold("Removing shell aliases.") +
|
||||
|
|
@ -52,7 +55,7 @@ export async function teardown() {
|
|||
ui.emptyLine();
|
||||
ui.writeInformation(`Please restart your terminal to apply the changes.`);
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (/** @type {any} */ error) {
|
||||
ui.writeError(
|
||||
`Failed to remove shell aliases: ${error.message}. Please check your shell configuration.`
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,11 @@
|
|||
import { spawn, execSync } from "child_process";
|
||||
import os from "os";
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function sanitizeShellArgument(arg) {
|
||||
// If argument contains shell metacharacters, wrap in double quotes
|
||||
// and escape characters that are special even inside double quotes
|
||||
|
|
@ -11,6 +16,11 @@ function sanitizeShellArgument(arg) {
|
|||
return arg;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function hasShellMetaChars(arg) {
|
||||
// Shell metacharacters that need escaping
|
||||
// These characters have special meaning in shells and need to be quoted
|
||||
|
|
@ -20,12 +30,23 @@ function hasShellMetaChars(arg) {
|
|||
return shellMetaChars.test(arg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} arg
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function escapeDoubleQuoteContent(arg) {
|
||||
// Escape special characters for shell safety
|
||||
// This escapes ", $, `, and \ by prefixing them with a backslash
|
||||
return arg.replace(/(["`$\\])/g, "\\$1");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} command
|
||||
* @param {string[]} args
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function buildCommand(command, args) {
|
||||
if (args.length === 0) {
|
||||
return command;
|
||||
|
|
@ -36,11 +57,17 @@ function buildCommand(command, args) {
|
|||
return `${command} ${escapedArgs.join(" ")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} command
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function resolveCommandPath(command) {
|
||||
// command will be "npm", "yarn", etc.
|
||||
// Use 'command -v' to find the full path
|
||||
const fullPath = execSync(`command -v ${command}`, {
|
||||
encoding: "utf8",
|
||||
// @ts-expect-error shell is a string option
|
||||
shell: true,
|
||||
}).trim();
|
||||
|
||||
|
|
@ -51,6 +78,13 @@ function resolveCommandPath(command) {
|
|||
return fullPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} command
|
||||
* @param {string[]} args
|
||||
* @param {import("child_process").SpawnOptions} options
|
||||
*
|
||||
* @returns {Promise<{status: number, stdout: string, stderr: string}>}
|
||||
*/
|
||||
export async function safeSpawn(command, args, options = {}) {
|
||||
// The command is always one of our supported package managers.
|
||||
// It should always be alphanumeric or _ or -
|
||||
|
|
@ -87,6 +121,7 @@ export async function safeSpawn(command, args, options = {}) {
|
|||
|
||||
child.on("close", (code) => {
|
||||
resolve({
|
||||
// @ts-expect-error code can be null
|
||||
status: code,
|
||||
stdout: stdout,
|
||||
stderr: stderr,
|
||||
|
|
|
|||
21
packages/safe-chain/tsconfig.json
Normal file
21
packages/safe-chain/tsconfig.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["es2023"],
|
||||
"module": "node16",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "node16",
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"noEmit": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.js",
|
||||
"bin/**/*.js"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"src/**/*.spec.js"
|
||||
]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue