🔩

Node.js をバージョンアップしたら safe-chain により Unknown command: "npm" のエラーになった

に公開

概要

Node.js のバージョンを、20.x から 24.x にバージョンアップしました。
その後 npm でコマンドを実行すると、Unknown command: "npm" とエラーになり、npm コマンドが実行できなくなりました。
こちらの解決策を記載します。

エラー内容

$ npm run build
Warning: safe-chain is not available to protect you from installing malware. npm will run without it.
Install safe-chain by using npm install -g @aikidosec/safe-chain.
Unknown command: "npm"

To see a list of supported npm commands, run:
  npm help

前提・環境

  • nvm: v0.40.3
  • Node.js: v24.13.0
  • npm: v11.6.2
  • @aikidosec/safe-chain を使用している

結論

  • safe-chain を再度 install する
curl -fsSL https://github.com/AikidoSec/safe-chain/releases/latest/download/install-safe-chain.sh | sh
  • 下記のようなログが流れていれば、成功
[INFO] Fetching latest release version...
[INFO] Installing safe-chain 1.4.1
[INFO] Detected nvm installation(s) of @aikidosec/safe-chain
[INFO] Uninstalling from all Node versions...
[INFO]   Removing from Node v20.19.5...
[INFO]   Successfully uninstalled from Node v20.19.5
[INFO] Detected platform: macos-x64
[INFO] Creating installation directory: /***/.safe-chain/bin
[INFO] Downloading from: https://github.com/AikidoSec/safe-chain/releases/download/1.4.1/safe-chain-macos-x64
[INFO] Binary installed to: /***/.safe-chain/bin/safe-chain
[INFO] Running safe-chain setup ...
Setting up shell aliases. This will wrap safe-chain around npm, npx, yarn, pnpm, pnpx, bun, bunx, uv, pip, pip3, poetry, python, python3, and pipx commands.

Detected 2 supported shell(s): Zsh, Bash.
- Zsh: Setup successful
- Bash: Setup successful

Please restart your terminal to apply the changes.
  • npm が実行できるか確認
npm run build

原因

原因は、@aikidosec/safe-chain が、特定の Node.js バージョンに紐づいて install されていることでした。

safe-chain 有効時の npm の挙動

safe-chain は、npm 等で package を install する際、汚染されたパッケージがないかなどを事前にチェックし回避するためのツールです。
上記のため、npm コマンドを下記のように上書きしています。

$ which npm
npm () {
	if [[ "$1" == "-v" || "$1" == "--version" ]] && [[ $# -eq 1 ]]
	then
		command npm "$@"
		return
	fi
	wrapSafeChainCommand "npm" "$@"
}

しかし、Node.js アップデート後に npm run xxx を実行すると、safe-chain を無視して npm コマンドを実行しようとし、その結果失敗するようです。

$ npm run build
Warning: safe-chain is not available to protect you from installing malware. npm will run without it.

safe-chain 再 install で解決する理由

install 時のログを見るとわかるように、古い Node 用に install されたファイルを uninstall しています。

$ curl -fsSL https://github.com/AikidoSec/safe-chain/releases/latest/download/install-safe-chain.sh | sh

...
[INFO] Uninstalling from all Node versions...
[INFO]   Removing from Node v20.19.5...
[INFO]   Successfully uninstalled from Node v20.19.5
...

uninstall し、再度新しいバージョン用に install することで、正しく npm コマンドが機能するようになります。

まとめ

Node.js の脆弱性対応によるバージョンアップを行ったところエラーになり、少し詰まったので、自分用に残しておきました。
参考になれば幸いです。

普段はTwitter(X)で、個人開発での学びや、作ったサービスの宣伝をしています。
よければフォローいただけると嬉しいです。
https://x.com/tea_____19

最後まで読んでいただき、ありがとうございました。

参考

下記を参考にさせていただきました。
https://zenn.dev/bisque/scraps/55e98c84259576

Discussion