Mastra npm Supply Chain Attack: Inside the North Korean Operation That Compromised 140+ Packages with Nodejs Implants and PowerShell Backdoors + Video

Listen to this Post

Featured Image

Introduction:

The npm ecosystem has become a prime battleground for sophisticated nation-state adversaries, with the latest victim being the Mastra framework—an AI agent development toolkit. Microsoft Threat Intelligence recently uncovered a massive supply-chain attack impacting over 140 packages within the Mastra ecosystem, where threat actors hijacked a legitimate maintainer account to distribute a typosquat package that deploys a stealthy Node.js implant and a PowerShell backdoor. This incident, attributed with high confidence to Sapphire Sleet—a North Korean state-sponsored group notorious for targeting financial and cryptocurrency sectors—demonstrates how a single compromised account can cascade into a widespread breach affecting thousands of developers worldwide.

Learning Objectives:

  • Understand the mechanics of the Mastra npm supply-chain attack and how typosquatting combined with account hijacking enabled widespread compromise
  • Identify indicators of compromise (IoCs) and detection strategies for malicious npm packages with post-install hooks
  • Master mitigation techniques including registry auditing, dependency pinning, and CI/CD pipeline hardening
  • Learn to implement Windows, macOS, and Linux persistence detection and removal procedures
  • Develop incident response workflows for supply-chain attacks targeting developer environments

You Should Know:

1. Attack Vector: Hijacked Maintainer Account and Typosquatting

The intrusion began when attackers compromised the “ehindero” npm maintainer account, which held publishing rights across the entire Mastra ecosystem. Using this privileged access, the threat actors injected a malicious dependency named `easy-day-js` into multiple legitimate Mastra packages. This rogue package was meticulously crafted to impersonate the hugely popular `dayjs` library, which typically sees over 57 million weekly downloads—a classic typosquatting technique designed to evade casual inspection.

The attackers employed a staged delivery pattern, first publishing a clean bait version of the typosquat package before pushing a weaponized update just hours later. This two-phase approach allowed the malicious code to bypass initial security reviews and gain a foothold before the true payload was introduced.

Step-by-step guide to detecting typosquat packages:

  1. Audit your dependencies for suspicious package names that closely resemble popular libraries:
    List all installed packages and flag potential typosquats
    npm ls --depth=0 | grep -E "-(js|core|util|lib)$"
    

  2. Compare package versions against the official registry to identify unauthorized updates:

    Check package metadata for recent publish dates
    npm view easy-day-js time --json
    

  3. Examine maintainer history for accounts with unusual publishing patterns:

    Query npm registry for maintainer activity
    npm owner ls <package-1ame>
    

  4. Implement package name allowlisting in your CI/CD pipeline:

    // .npmrc or package.json allowlist
    {
    "allowedPackages": ["dayjs", "lodash", "express"],
    "blockedPatterns": [".-js$", ".-core$"]
    }
    

2. Post-Install Hook Execution and Dropper Mechanism

What makes this attack particularly insidious is that the malicious code executed via an npm post-install hook, meaning developers did not even need to import the package into their code. Simply running an installation or update command on a compromised version was enough to execute a hidden dropper script named setup.cjs.

The initial dropper used rotated string arrays and Base64 encoding to obfuscate its true intent from static analysis tools. Once activated, it immediately disabled TLS certificate verification to mask its command-and-control (C2) traffic, then downloaded a secondary Node.js payload from an attacker-controlled server. It also dropped hidden tracking files into the operating system’s temporary directory to mark the infection and prevent re-execution.

Step-by-step guide to detecting and analyzing post-install hooks:

1. Inspect package scripts for suspicious post-install hooks:

 View package.json scripts
cat node_modules/<package>/package.json | jq '.scripts'

Recursively search for postinstall hooks across all dependencies
find node_modules -1ame "package.json" -exec grep -l "postinstall" {} \;
  1. Monitor npm install commands in your CI/CD logs for unexpected script execution:
    Enable verbose logging during installation
    npm install --loglevel=verbose 2>&1 | tee install.log
    

3. Analyze the dropper script for obfuscation patterns:

 Deobfuscate Base64-encoded strings
echo "<base64-string>" | base64 -d

Identify rotated string arrays (common in malware)
grep -E "[['\"][a-zA-Z]+\s,\s['\"][a-zA-Z]+" setup.cjs

4. Monitor outbound connections during package installation:

 Linux: Monitor network connections in real-time
sudo tcpdump -i any -1 "host 23.254.164.92 or host 23.254.164.123"

Windows: Use netstat to identify established connections
netstat -ano | findstr ESTABLISHED

3. Cross-Platform Persistence Mechanisms

To maintain access to infected machines, the malware established persistence across multiple operating systems:

  • Windows: Created hidden launch files masquerading as legitimate Node.js protocols using Windows Registry keys
  • macOS: Deployed LaunchAgents to execute automatically upon user login
  • Linux: Installed systemd units for persistent background execution

Step-by-step guide to detecting and removing persistence mechanisms:

Windows Registry Persistence Detection:

 Query common Node.js persistence keys
Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" | 
Where-Object { $_.Value -like "node" }

Get-ChildItem -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" | 
Where-Object { $_.Value -like "node" }

Check for hidden launch files in suspicious locations
dir C:\Users\AppData\Roaming\Microsoft\Windows\Start` Menu\Programs\Startup\node -Recurse

macOS LaunchAgent Persistence Detection:

 List all LaunchAgents and grep for Node.js entries
ls -la ~/Library/LaunchAgents/ | grep -i node
ls -la /Library/LaunchAgents/ | grep -i node

Examine plist files for suspicious execution paths
find ~/Library/LaunchAgents -1ame ".plist" -exec plutil -p {} \; | grep -A5 -B5 "node"

Linux systemd Persistence Detection:

 List all systemd services and check for Node.js execution
systemctl list-units --type=service --all | grep -i node

Examine service unit files for suspicious commands
find /etc/systemd/system -1ame ".service" -exec grep -l "node" {} \;

Check for user-level systemd services
ls -la ~/.config/systemd/user/ | grep -i node

4. Data Exfiltration: Cryptocurrency Wallet Targeting

Once embedded, the implant actively hunted for sensitive data, explicitly targeting 166 different cryptocurrency wallet browser extensions, as well as browser histories and detailed system metadata. This targeted approach aligns with Sapphire Sleet’s known motivation: stealing cryptocurrency and valuable intellectual property.

Step-by-step guide to detecting cryptocurrency wallet theft indicators:

1. Monitor browser extension directories for unauthorized access:

 Linux: Check for unusual access to Chrome extension folders
sudo auditctl -w /home//.config/google-chrome/Default/Extensions/ -p rwxa -k chrome_extensions

Windows: Monitor extension directories using PowerShell
Get-ChildItem -Path "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Extensions" -Recurse | 
Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-24) }

2. Detect browser history exfiltration:

 Monitor access to browser history databases
lsof | grep -E "History|Cookies|Login Data" | grep -v chrome
  1. Identify cryptocurrency wallet extensions that may have been targeted:
    List all installed Chrome extensions
    ls ~/.config/google-chrome/Default/Extensions/
    
    Cross-reference with known wallet extension IDs
    (Maintain a list of known wallet extension IDs for your organization)
    

5. PowerShell Backdoor and Anti-Forensic Techniques

For high-value targets, Sapphire Sleet deployed a secondary PowerShell backdoor to gain ultimate control. This script executed anti-forensic cleanup commands to wipe its own command history and established SYSTEM-level privileges by creating a malicious Windows service that ran automatically at boot, ensuring attackers retained an interactive, hands-on-keyboard connection to the compromised network.

Step-by-step guide to detecting and removing the PowerShell backdoor:

1. Check for suspicious PowerShell services:

 List all services and look for PowerShell-related entries
Get-Service | Where-Object { $<em>.DisplayName -like "powershell" -or $</em>.Name -like "ps" }

Examine service binary paths for encoded commands
Get-WmiObject Win32_Service | Where-Object { $_.PathName -like "powershell" } | 
Select-Object Name, DisplayName, PathName, StartName
  1. Review PowerShell command history (note: attackers may have wiped this):
    Check PSReadLine history
    Get-Content (Get-PSReadLineOption).HistorySavePath
    
    Check Event Logs for PowerShell execution
    Get-WinEvent -LogName "Windows PowerShell" | Where-Object { $_.Message -like "encoded" }
    

3. Detect SYSTEM-level service creation:

 Look for recently created services with SYSTEM privileges
Get-WinEvent -LogName "System" | Where-Object { $<em>.Id -eq 7045 } | 
Where-Object { $</em>.Message -like "SYSTEM" } | 
Select-Object TimeCreated, Message

4. Monitor for anti-forensic commands:

 Look for evidence of command history wiping
Get-WinEvent -LogName "Windows PowerShell" | Where-Object { $_.Message -like "Clear-History" }

Check for suspicious Scheduled Tasks
Get-ScheduledTask | Where-Object { $<em>.TaskPath -like "MicrosoftWindows" -and $</em>.Actions -like "powershell" }

6. Indicators of Compromise (IoCs) and Detection Strategy

Microsoft has released specific IoCs for this campaign:

| Indicator | Type | Description |

|–||-|

| 23.254.164.92 | IP address | Primary C2 server |
| 23.254.164.123 | IP address | Secondary C2 address |
| https[:]//23[.]254[.]164[.]92:8000/update/49890878 | URL | Payload download endpoint |
| easy-day-js | Package name | Malicious typosquat package |

| setup.cjs | Filename | Dropper script |

Step-by-step guide to implementing IoC detection:

1. Configure network monitoring for C2 communications:

 Linux: Block C2 IPs using iptables
sudo iptables -A OUTPUT -d 23.254.164.92 -j DROP
sudo iptables -A OUTPUT -d 23.254.164.123 -j DROP

Windows: Add firewall rules
New-1etFirewallRule -DisplayName "Block C2 IP" -Direction Outbound -RemoteAddress 23.254.164.92 -Action Block
New-1etFirewallRule -DisplayName "Block C2 IP" -Direction Outbound -RemoteAddress 23.254.164.123 -Action Block
  1. Implement YARA rules for detecting the Node.js implant:
    rule Mastra_NodeJS_Implant {
    meta:
    description = "Detects Mastra supply chain attack Node.js implant"
    author = "Security Team"
    strings:
    $s1 = "setup.cjs" fullword
    $s2 = "easy-day-js" fullword
    $s3 = "49890878" fullword
    $s4 = "TLS certificate verification" fullword
    condition:
    any of them
    }
    

3. Configure SIEM alerts for suspicious npm activity:

{
"alert_name": "Suspicious npm Package Installation",
"conditions": [
"process_name: npm",
"command_line: install",
"network_destination: 23.254.164."
],
"severity": "high"
}

What Undercode Say:

  • Key Takeaway 1: The Mastra attack demonstrates that even well-maintained open-source ecosystems are vulnerable to nation-state adversaries. The compromise of a single maintainer account with broad publishing rights cascaded into a massive supply-chain breach affecting over 140 packages—highlighting the critical need for robust account security, including hardware-backed 2FA and least-privilege access models for npm publishers.

  • Key Takeaway 2: The use of post-install hooks as an execution vector is particularly dangerous because it bypasses traditional code review processes. Developers don’t need to import or execute the malicious code explicitly—merely running `npm install` on a compromised version triggers the payload. Organizations must implement dependency scanning that inspects package scripts, not just source code, and consider blocking packages with suspicious post-install hooks in production environments.

Analysis:

The Mastra npm supply-chain attack represents a significant escalation in the sophistication of software supply-chain threats. By combining account hijacking, typosquatting, staged delivery, and cross-platform persistence, Sapphire Sleet has demonstrated an operational maturity that rivals advanced persistent threat groups. The fact that the attackers specifically targeted 166 cryptocurrency wallet extensions reveals a clear financial motivation, aligning with North Korea’s known cyber-espionage and revenue-generation objectives.

What makes this attack particularly concerning is the stealth achieved through TLS certificate verification disabling and anti-forensic cleanup—techniques typically associated with high-end intrusion sets. The attackers’ ability to maintain interactive access via a SYSTEM-level PowerShell service suggests they anticipated long-term persistence and hands-on-keyboard activity, rather than opportunistic data theft. For defenders, this incident underscores the necessity of treating developer workstations and CI/CD pipelines as critical infrastructure requiring the same security rigor as production environments.

Prediction:

  • +1 The widespread disclosure of this attack will accelerate the adoption of software supply-chain security frameworks like SLSA and Sigstore, as organizations recognize that traditional vulnerability scanning is insufficient to detect sophisticated typosquatting and account hijacking attacks.

  • -1 We can expect a surge in similar attacks targeting other popular npm frameworks and maintainers with broad publishing permissions, as Sapphire Sleet’s success demonstrates the high return on investment for supply-chain compromises.

  • -1 The use of npm post-install hooks as an attack vector will likely be adopted by other threat groups, potentially leading to a wave of supply-chain attacks across the JavaScript ecosystem before mitigation measures are widely implemented.

  • +1 npm and other package registries will be forced to implement stricter publishing controls, including mandatory 2FA for maintainers, automated typosquatting detection, and enhanced post-install hook sandboxing—ultimately making the ecosystem more resilient.

  • -1 Developer trust in open-source dependencies may erode, leading to increased scrutiny and slower adoption of new packages, which could temporarily hinder innovation in the Node.js ecosystem.

▶️ Related Video (68% Match):

https://www.youtube.com/watch?v=69F9IuBWb-E

🎯Let’s Practice For Free:

🎓 Live Courses & Certifications:

Join Undercode Academy for Verified Certifications

🚀 Request a Custom Project:

Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands

IT/Security Reporter URL:

Reported By: Varshu25 Mastra – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

💬 Whatsapp | 💬 Telegram

📢 Follow UndercodeTesting & Stay Tuned:

𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky