Skip to content

Commit

Permalink
Allow wgpw to prompt for a password through stdin (wg-easy#1348)
Browse files Browse the repository at this point in the history
* Allow wgpw to prompt for a password through stdin

If the user does not pass the password as a parameter, they are prompted
for it through stdin.
The password is not echoed back, just like any other command-line log-in
prompt (ie. sudo).

* Fix lint errors in wgpw
  • Loading branch information
mcmacker4 authored Sep 3, 2024
1 parent 4758c0d commit 11872de
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
6 changes: 6 additions & 0 deletions How_to_generate_an_bcrypt_hash.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ To generate a bcrypt password hash using docker, run the following command :
docker run ghcr.io/wg-easy/wg-easy wgpw YOUR_PASSWORD
PASSWORD_HASH='$2b$12$coPqCsPtcFO.Ab99xylBNOW4.Iu7OOA2/ZIboHN6/oyxca3MWo7fW' // literally YOUR_PASSWORD
```
If a password is not provided, the tool will prompt you for one :
```sh
docker run ghcr.io/wg-easy/wg-easy wgpw
Enter your password: // hidden prompt, type in your password
PASSWORD_HASH='$2b$12$coPqCsPtcFO.Ab99xylBNOW4.Iu7OOA2/ZIboHN6/oyxca3MWo7fW'
```

**Important** : make sure to enclose your password in **single quotes** when you run `docker run` command :

Expand Down
30 changes: 29 additions & 1 deletion src/wgpw.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

// Import needed libraries
import bcrypt from 'bcryptjs';
import { Writable } from 'stream';
import readline from 'readline';

// Function to generate hash
const generateHash = async (password) => {
Expand Down Expand Up @@ -31,19 +33,45 @@ const comparePassword = async (password, hash) => {
}
};

const readStdinPassword = () => {
return new Promise((resolve) => {
process.stdout.write('Enter your password: ');

const rl = readline.createInterface({
input: process.stdin,
output: new Writable({
write(_chunk, _encoding, callback) {
callback();
},
}),
terminal: true,
});

rl.question('', (answer) => {
rl.close();
// Print a new line after password prompt
process.stdout.write('\n');
resolve(answer);
});
});
};

(async () => {
try {
// Retrieve command line arguments
const args = process.argv.slice(2); // Ignore the first two arguments
if (args.length > 2) {
throw new Error('Usage : wgpw YOUR_PASSWORD [HASH]');
throw new Error('Usage : wgpw [YOUR_PASSWORD] [HASH]');
}

const [password, hash] = args;
if (password && hash) {
await comparePassword(password, hash);
} else if (password) {
await generateHash(password);
} else {
const password = await readStdinPassword();
await generateHash(password);
}
} catch (error) {
// eslint-disable-next-line no-console
Expand Down

0 comments on commit 11872de

Please sign in to comment.