Merge branch 'main' into verbose-logging

This commit is contained in:
Sander Declerck 2025-11-03 11:37:47 +01:00
commit be6a6dccd9
No known key found for this signature in database
62 changed files with 1243 additions and 41 deletions

View file

@ -3,6 +3,16 @@ import fetch from "make-fetch-happen";
const malwareDatabaseUrl =
"https://malware-list.aikido.dev/malware_predictions.json";
/**
* @typedef {Object} 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",

View file

@ -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>, versions?: Record<string, unknown>} | 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) && distTags[versionRange]) {
// 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);

View file

@ -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=";

View file

@ -3,13 +3,22 @@ import path from "path";
import os from "os";
import { ui } from "../environment/userInteraction.js";
/**
* @returns {number}
*/
export function getScanTimeout() {
const config = readConfigFile();
return (
parseInt(process.env.AIKIDO_SCAN_TIMEOUT_MS) || config.scanTimeout || 10000 // Default to 10 seconds
);
const config = /** @type {{scanTimeout?: number}} */ (readConfigFile());
// @ts-expect-error values of process.env can be string | undefined
return parseInt(process.env.AIKIDO_SCAN_TIMEOUT_MS) || config.scanTimeout || 10000 // Default to 10 seconds
}
/**
* @param {import("../api/aikido.js").MalwarePackage[]} data
* @param {string | number} version
*
* @returns {void}
*/
export function writeDatabaseToLocalCache(data, version) {
try {
const databasePath = getDatabasePath();
@ -24,6 +33,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 +67,9 @@ export function readDatabaseFromLocalCache() {
}
}
/**
* @returns {unknown}
*/
function readConfigFile() {
const configFilePath = getConfigFilePath();
@ -66,6 +81,9 @@ function readConfigFile() {
return JSON.parse(data);
}
/**
* @returns {string}
*/
function getDatabasePath() {
const aikidoDir = getAikidoDirectory();
return path.join(aikidoDir, "malwareDatabase.json");
@ -76,10 +94,16 @@ function getDatabaseVersionPath() {
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");

View file

@ -27,12 +27,22 @@ function emptyLine() {
writeInformation("");
}
/**
* @param {string} message
* @param {...any} optionalParams
* @returns {void}
*/
function writeInformation(message, ...optionalParams) {
if (isSilentMode()) return;
writeOrBuffer(() => console.log(message, ...optionalParams));
}
/**
* @param {string} message
* @param {...any} optionalParams
* @returns {void}
*/
function writeWarning(message, ...optionalParams) {
if (isSilentMode()) return;
@ -42,6 +52,11 @@ function writeWarning(message, ...optionalParams) {
writeOrBuffer(() => console.warn(message, ...optionalParams));
}
/**
* @param {string} message
* @param {...any} optionalParams
* @returns {void}
*/
function writeError(message, ...optionalParams) {
if (!isCi()) {
message = chalk.red(message);
@ -71,6 +86,19 @@ function writeOrBuffer(messageFunction) {
}
}
/**
* @typedef {Object} 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 {

View file

@ -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) {
process.on("SIGINT", handleProcessTermination);
process.on("SIGTERM", handleProcessTermination);
@ -14,6 +18,23 @@ export async function main(args) {
const proxy = createSafeChainProxy();
await proxy.startServer();
// 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);
});
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);
});
try {
// This parses all the --safe-chain arguments and removes them from the args array
args = initializeCliArguments(args);
@ -52,7 +73,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

View file

@ -1,3 +1,8 @@
/**
* @param {string[]} args
* @param {...string} commandArgs
* @returns {boolean}
*/
export function matchesCommand(args, ...commandArgs) {
if (args.length < commandArgs.length) {
return false;

View file

@ -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),
@ -13,6 +16,9 @@ export function createBunPackageManager() {
};
}
/**
* @returns {import("../currentPackageManager.js").PackageManager}
*/
export function createBunxPackageManager() {
return {
runCommand: (args) => runBunCommand("bunx", args),
@ -24,14 +30,20 @@ export function createBunxPackageManager() {
};
}
/**
* @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 {

View file

@ -10,10 +10,32 @@ import {
} from "./pnpm/createPackageManager.js";
import { createYarnPackageManager } from "./yarn/createPackageManager.js";
/**
* @type {{packageManagerName: PackageManager | null}}
*/
const state = {
packageManagerName: null,
};
/**
* @typedef {Object} GetDependencyUpdatesResult
* @property {string} name
* @property {string} version
* @property {string} type
*/
/**
* @typedef {Object} PackageManager
* @property {(args: string[]) => Promise<{ status: number }>} runCommand
* @property {(args: string[]) => boolean} isSupportedCommand
* @property {(args: string[]) => Promise<GetDependencyUpdatesResult[]> | GetDependencyUpdatesResult[]} getDependencyUpdatesForCommand
*/
/**
* @param {string} packageManagerName
*
* @return {PackageManager}
*/
export function initializePackageManager(packageManagerName) {
if (packageManagerName === "npm") {
state.packageManagerName = createNpmPackageManager();

View file

@ -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 {ReturnType<import("../currentPackageManager.js").PackageManager["getDependencyUpdatesForCommand"]>}
*/
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) {

View file

@ -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 {Object} CommandArgumentScanner
* @property {(args: string[]) => Promise<ScanResult[]> | 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);

View file

@ -1,3 +1,6 @@
/**
* @returns {import("./commandArgumentScanner.js").CommandArgumentScanner}
*/
export function nullScanner() {
return {
scan: () => [],

View file

@ -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) {

View file

@ -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() ??

View file

@ -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",

View file

@ -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;

View file

@ -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");
}

View file

@ -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();

View file

@ -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
};
}
/**
* @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);

View file

@ -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

View file

@ -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 {

View file

@ -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 {ReturnType<import("../currentPackageManager.js").PackageManager["getDependencyUpdatesForCommand"]>}
*/
function getDependencyUpdatesForCommand(args, isPnpx) {
if (isPnpx) {
return scanner.scan(args);

View file

@ -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);

View file

@ -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

View file

@ -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 {

View file

@ -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;

View file

@ -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);

View file

@ -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

View file

@ -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.

View file

@ -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) {

View file

@ -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) {
ui.writeVerbose(`Safe-chain: Set up MITM tunnel for ${req.url}`);
const { hostname } = new URL(`http://${req.url}`);
@ -18,6 +23,16 @@ export function mitmConnect(req, clientSocket, isAllowed) {
const server = createHttpsServer(hostname, 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) {
clientSocket.end();
}
});
// Establish the connection
clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
@ -25,10 +40,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}`;
@ -43,15 +70,21 @@ function createHttpsServer(hostname, isAllowed) {
forwardRequest(req, hostname, res);
}
return https.createServer(
const server = https.createServer(
{
key: cert.privateKey,
cert: cert.certificate,
},
handleRequest
);
return server;
}
/**
* @param {string} url
* @returns {string}
*/
function getRequestPathAndQuery(url) {
if (url.startsWith("http://") || url.startsWith("https://")) {
const parsedUrl = new URL(url);
@ -60,6 +93,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);
@ -71,6 +109,11 @@ function forwardRequest(req, hostname, res) {
res.end("Bad Gateway");
});
req.on("error", (err) => {
ui.writeError(`Safe-chain: Error reading client request: ${err.message}`);
proxyReq.destroy();
});
req.on("data", (chunk) => {
proxyReq.write(chunk);
});
@ -83,7 +126,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,
@ -92,7 +143,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) {
@ -100,6 +153,17 @@ function createProxyRequest(hostname, req, res) {
}
const proxyReq = https.request(options, (proxyRes) => {
proxyRes.on("error", (err) => {
ui.writeError(
`Safe-chain: Error reading upstream response: ${err.message}`
);
if (!res.headersSent) {
res.writeHead(502);
res.end("Bad Gateway");
}
});
// @ts-expect-error statusCode might be undefined
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
});

View file

@ -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;

View file

@ -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);
@ -43,8 +52,13 @@ export function handleHttpProxyRequest(req, res) {
}
)
.on("error", (err) => {
res.writeHead(502);
res.end(`Bad Gateway: ${err.message}`);
if (!res.headersSent) {
res.writeHead(502);
res.end(`Bad Gateway: ${err.message}`);
} else {
// Headers already sent, just destroy the response
res.destroy();
}
});
req.on("error", () => {

View file

@ -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
@ -114,6 +143,10 @@ function handleConnect(req, clientSocket, head) {
}
}
/**
* @param {string} url
* @returns {Promise<boolean>}
*/
async function isAllowedUrl(url) {
const { packageName, version } = parsePackageFromUrl(url);

View file

@ -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,15 +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}`);
clientSocket.on("error", () => {
// NO-OP
// This can happen if the client TCP socket sends RST instead of FIN.
// Not subscribing to 'close' event will cause node to throw and crash.
});
// @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);
@ -37,6 +46,14 @@ function tunnelRequestToDestination(req, clientSocket, head) {
clientSocket.pipe(serverSocket);
});
clientSocket.on("error", () => {
// This can happen if the client TCP socket sends RST instead of FIN.
// Not subscribing to 'error' event will cause node to throw and crash.
if (serverSocket.writable) {
serverSocket.end();
}
});
serverSocket.on("error", (err) => {
ui.writeError(
`Safe-chain: error connecting to ${hostname}:${port} - ${err.message}`
@ -47,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,
@ -103,6 +127,13 @@ function tunnelRequestViaProxy(req, clientSocket, head, proxyUrl) {
if (clientSocket.writable) {
clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n");
}
} else {
ui.writeError(
`Safe-chain: proxy socket error after connection - ${err.message}`
);
if (clientSocket.writable) {
clientSocket.end();
}
}
});

View file

@ -4,6 +4,25 @@ import {
openMalwareDatabase,
} from "../malwareDatabase.js";
/**
* @typedef {Object} PackageChange
* @property {string} name
* @property {string} version
* @property {string} type
*/
/**
* @typedef {Object} 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 = [];
@ -41,6 +60,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 [];

View file

@ -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:"));

View file

@ -8,6 +8,13 @@ import {
} from "../config/configFile.js";
import { ui } from "../environment/userInteraction.js";
/**
* @typedef {Object} 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;

View file

@ -3,6 +3,15 @@ import * as os from "os";
import fs from "fs";
import path from "path";
/**
* @typedef {Object} 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,6 +109,13 @@ function shouldRemoveLine(line, pattern) {
return true;
}
/**
* @param {string} filePath
* @param {string} line
* @param {string} [eol]
*
* @returns {void}
*/
export function addLineToFile(filePath, line, eol) {
createFileIfNotExists(filePath);
@ -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;

View file

@ -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

View file

@ -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;
}

View file

@ -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 {Object} 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}`
);

View file

@ -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,

View file

@ -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,

View file

@ -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,

View file

@ -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,

View file

@ -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}`
);

View file

@ -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.`
);

View file

@ -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,