|
| 1 | +import { exec } from 'child_process' |
| 2 | +import fs from 'fs' |
| 3 | +import homedir from 'os' |
| 4 | +import readline from 'readline' |
| 5 | + |
| 6 | +console.log(` |
| 7 | + _____ _ _ |
| 8 | +| __|___ ___| |_ ___| |_ |
| 9 | +|__ | . | _| '_| -_| _| |
| 10 | +|_____|___|___|_,_|___|_| |
| 11 | +
|
| 12 | +`) |
| 13 | + |
| 14 | +/** |
| 15 | + * @param {string} query |
| 16 | + * @returns {void} |
| 17 | + */ |
| 18 | +const installSafeNpm = (query) => { |
| 19 | + const rl = readline.createInterface({ |
| 20 | + input: process.stdin, |
| 21 | + output: process.stdout, |
| 22 | + }) |
| 23 | + return askQuestion(rl, query) |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * @param {any} rl |
| 28 | + * @param {string} query |
| 29 | + * @returns {void} |
| 30 | + */ |
| 31 | +const askQuestion = (rl, query) => { |
| 32 | + rl.question(query, (/** @type {string} */ ans) => { |
| 33 | + if (ans.toLowerCase() === 'y') { |
| 34 | + const bashFile = `${homedir.homedir()}/.bashrc` |
| 35 | + const zshBashFile = `${homedir.homedir()}/.zshrc` |
| 36 | + |
| 37 | + try { |
| 38 | + if (fs.existsSync(bashFile)) { |
| 39 | + addAlias(bashFile) |
| 40 | + } else if (fs.existsSync(zshBashFile)) { |
| 41 | + addAlias(zshBashFile) |
| 42 | + } |
| 43 | + } catch (e) { |
| 44 | + throw new Error('There was an issue setting up the alias.', { cause: e }) |
| 45 | + } |
| 46 | + rl.close() |
| 47 | + } else if (ans.toLowerCase() !== 'n') { |
| 48 | + askQuestion(rl, 'Incorrect input: please enter either y (yes) or n (no): ') |
| 49 | + } else { |
| 50 | + rl.close() |
| 51 | + } |
| 52 | + }) |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * @param {string} file |
| 57 | + * @returns {void} |
| 58 | + */ |
| 59 | +const addAlias = (file) => { |
| 60 | + exec(`echo "alias npm='socket npm' \nalias npx='socket npx'" >> ${file}`, (err, _, stderr) => { |
| 61 | + if (err) { |
| 62 | + return new Error(`There was an error setting up the alias: ${stderr}`) |
| 63 | + } |
| 64 | + console.log(`The alias was added to ${file}. Running 'npm install' will now be wrapped in Socket's "safe npm" 🎉`) |
| 65 | + }) |
| 66 | +} |
| 67 | + |
| 68 | +installSafeNpm(`The Socket CLI is now successfully installed! 🎉 |
| 69 | +
|
| 70 | +To better protect yourself against supply-chain attacks, our "safe npm" wrapper can warn you about malicious packages whenever you run 'npm install'. |
| 71 | +
|
| 72 | +Do you want to install "safe npm" (this will create an alias to the socket-npm command)? (y/n)`) |
0 commit comments