2 * Copyright 2016, Joyent, Inc. All rights reserved.
3 * Author: Alex Wilson <alex.wilson@joyent.com>
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to
7 * deal in the Software without restriction, including without limitation the
8 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 * sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28 const mod_tty = require('tty');
29 const mod_fs = require('fs');
30 const mod_assert = require('assert-plus');
32 var BACKSPACE = String.fromCharCode(127);
36 function getPass(opts, cb) {
37 if (typeof (opts) === 'function' && cb === undefined) {
41 mod_assert.object(opts, 'options');
42 mod_assert.func(cb, 'callback');
44 mod_assert.optionalString(opts.prompt, 'options.prompt');
45 if (opts.prompt === undefined)
46 opts.prompt = 'Password';
48 openTTY(function (err, rfd, wfd, rtty, wtty) {
54 wtty.write(opts.prompt + ':');
56 rtty.setRawMode(true);
58 rtty.setEncoding('utf8');
61 rtty.on('data', onData);
63 function onData(data) {
64 var str = data.toString('utf8');
65 for (var i = 0; i < str.length; ++i) {
76 cb(new Error('Aborted'));
79 pw = pw.slice(0, pw.length - 1);
90 rtty.setRawMode(false);
92 rtty.removeListener('data', onData);
93 if (wfd !== undefined && wfd !== rfd) {
95 mod_fs.closeSync(wfd);
97 if (rfd !== undefined) {
99 mod_fs.closeSync(rfd);
105 function openTTY(cb) {
106 mod_fs.open('/dev/tty', 'r+', function (err, rttyfd) {
107 if ((err && (err.code === 'ENOENT' || err.code === 'EACCES')) ||
108 (process.version.match(/^v0[.][0-8][.]/))) {
109 cb(null, undefined, undefined, process.stdin,
113 var rtty = new mod_tty.ReadStream(rttyfd);
114 mod_fs.open('/dev/tty', 'w+', function (err3, wttyfd) {
115 var wtty = new mod_tty.WriteStream(wttyfd);
120 cb(null, rttyfd, wttyfd, rtty, wtty);