@shieldfive/cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.mjs CHANGED
@@ -1,20 +1,24 @@
1
1
  #!/usr/bin/env node
2
- // ShieldFive CLI (`sf`) — scaffold.
2
+ // ShieldFive CLI (`sf`).
3
3
  //
4
4
  // sf encrypt <folder> encrypt each file locally (verified core demo)
5
- // sf push <folder> login -> unlock -> encrypt -> upload once
6
- // sf sync <folder> [--watch] keep the folder mirrored into your vault
5
+ // sf login [--idle=<hours>] sign in once; an agent holds the session in memory
6
+ // sf status is an agent running, and for which account
7
+ // sf logout [--everywhere] revoke the session and stop the agent
8
+ // sf push <folder> encrypt and upload every file, once
9
+ // sf sync <folder> [--watch] upload new and changed files
10
+ // sf verify <file>... is each file safely stored in your vault
7
11
  //
8
- // The offline crypto chain (unlock -> identity -> encrypt) is VERIFIED
9
- // (`npm test`), and the full upload pipeline (direct + multipart) is wired and
10
- // tested. Configure the live commands with env vars (see README) and run them
11
- // against your own ShieldFive account.
12
+ // push and sync use a running agent when there is one. When SF_EMAIL and
13
+ // SF_PASSWORD are set they sign in from those instead, exactly as before, so a
14
+ // script written for one account is never quietly redirected to an agent
15
+ // signed in as another. See docs/agent-design.md.
12
16
 
13
17
  import { webcrypto } from 'node:crypto'
14
18
  import { readFile, readdir, stat } from 'node:fs/promises'
15
- import { join } from 'node:path'
16
- import { createInterface } from 'node:readline'
19
+ import { join, resolve } from 'node:path'
17
20
 
21
+ import { promptHidden, promptLine } from './prompt.mjs'
18
22
  import { deriveVaultIdentity, encryptFileForVault } from './sfCrypto.mjs'
19
23
 
20
24
  function usage() {
@@ -22,16 +26,21 @@ function usage() {
22
26
  [
23
27
  'sf <command>',
24
28
  '',
25
- ' encrypt <folder> encrypt each file in <folder> locally (verified core)',
26
- ' push <folder> login -> unlock -> encrypt -> upload to your vault',
27
- ' sync <folder> [--watch] mirror new/changed files into your vault',
29
+ ' login [--idle=<hours>] sign in once and start an agent (default: locks after 8 h without use)',
30
+ ' status show whether an agent is running',
31
+ ' logout [--everywhere] revoke the session and stop the agent',
32
+ ' --everywhere also signs out your browser and phone',
33
+ ' push <folder> encrypt and upload every file in <folder>',
34
+ ' sync <folder> [--watch] upload new and changed files',
28
35
  ' [--interval=<seconds>] poll interval for --watch (default 5)',
36
+ ' verify <file>... report whether each file is safely in your vault',
37
+ ' encrypt <folder> encrypt each file locally, upload nothing',
29
38
  ' --help',
30
39
  '',
31
- 'push / sync need only your ShieldFive account:',
32
- ' SF_EMAIL, SF_PASSWORD [SF_VAULT_PASSWORD if your vault password differs]',
33
- 'If two-factor (TOTP) is enabled, you are prompted for a 6-digit code',
34
- '(or set SF_TOTP_CODE). SF_API_BASE_URL, SF_SUPABASE_URL, SF_SUPABASE_ANON_KEY',
40
+ 'After sf login, push / sync / verify go through the agent and need nothing',
41
+ 'in the environment. Without an agent, or when SF_EMAIL and SF_PASSWORD are',
42
+ 'set, push and sync sign in from those [SF_VAULT_PASSWORD if your vault',
43
+ 'password differs]. SF_API_BASE_URL, SF_SUPABASE_URL, SF_SUPABASE_ANON_KEY',
35
44
  'default to ShieldFive (override only for a development backend).',
36
45
  '',
37
46
  ].join('\n') + '\n',
@@ -76,6 +85,19 @@ const DEFAULTS = {
76
85
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRza2JtanBhbmVoY2tocXprY2xwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzAxMTc3MzEsImV4cCI6MjA4NTY5MzczMX0.AK7K8tyrAWFWgfaa6vvTveqmKiMrL2nY1m7qS9TII9U',
77
86
  }
78
87
 
88
+ function backendConfig() {
89
+ const e = process.env
90
+ return {
91
+ apiBaseUrl: e.SF_API_BASE_URL || DEFAULTS.apiBaseUrl,
92
+ supabaseUrl: e.SF_SUPABASE_URL || DEFAULTS.supabaseUrl,
93
+ anonKey: e.SF_SUPABASE_ANON_KEY || DEFAULTS.anonKey,
94
+ }
95
+ }
96
+
97
+ function envCredentialsSet() {
98
+ return Boolean(process.env.SF_EMAIL && process.env.SF_PASSWORD)
99
+ }
100
+
79
101
  function readLiveConfig() {
80
102
  const e = process.env
81
103
  const email = e.SF_EMAIL
@@ -85,34 +107,20 @@ function readLiveConfig() {
85
107
  if (!password) missing.push('SF_PASSWORD')
86
108
  if (missing.length) {
87
109
  throw new Error(
88
- `this command needs your ShieldFive account: set ${missing.join(' and ')}. ` +
89
- '(SF_API_BASE_URL, SF_SUPABASE_URL, and SF_SUPABASE_ANON_KEY default to ' +
90
- 'ShieldFive; override them only for a development backend.)',
110
+ `this command needs your ShieldFive account: run sf login, or set ` +
111
+ `${missing.join(' and ')}. (SF_API_BASE_URL, SF_SUPABASE_URL, and ` +
112
+ 'SF_SUPABASE_ANON_KEY default to ShieldFive; override them only for a ' +
113
+ 'development backend.)',
91
114
  )
92
115
  }
93
116
  return {
94
- apiBaseUrl: e.SF_API_BASE_URL || DEFAULTS.apiBaseUrl,
95
- supabaseUrl: e.SF_SUPABASE_URL || DEFAULTS.supabaseUrl,
96
- anonKey: e.SF_SUPABASE_ANON_KEY || DEFAULTS.anonKey,
117
+ ...backendConfig(),
97
118
  email,
98
119
  password,
99
120
  vaultPassword: e.SF_VAULT_PASSWORD || password,
100
121
  }
101
122
  }
102
123
 
103
- // Prompt for a single line on the terminal. A TOTP code is short-lived, not a
104
- // long-term secret, so echoing it is fine (unlike the password).
105
- function promptLine(question) {
106
- return new Promise((resolve, reject) => {
107
- const rl = createInterface({ input: process.stdin, output: process.stderr })
108
- rl.question(question, (answer) => {
109
- rl.close()
110
- resolve(answer)
111
- })
112
- rl.on('error', reject)
113
- })
114
- }
115
-
116
124
  // Source a TOTP code for the 2FA step-up: SF_TOTP_CODE if set (handy for
117
125
  // scripting), otherwise prompt interactively. Only invoked when the account
118
126
  // actually requires a step-up.
@@ -152,8 +160,240 @@ async function authAndUnlock(cfg) {
152
160
  return { accessToken, rootKey }
153
161
  }
154
162
 
163
+ async function runningAgent() {
164
+ const { agentStatus } = await import('./agent/client.mjs')
165
+ const status = await agentStatus()
166
+ return status?.unlocked ? status : null
167
+ }
168
+
169
+ /**
170
+ * Decide how push and sync authenticate. Environment credentials win when both
171
+ * are set: that is how these commands behaved before the agent existed, and it
172
+ * keeps a script that names an account from being redirected to whichever
173
+ * account the agent happens to hold.
174
+ */
175
+ async function chooseAuth() {
176
+ const agent = await runningAgent()
177
+ if (envCredentialsSet()) {
178
+ if (agent) {
179
+ process.stderr.write(
180
+ `SF_EMAIL and SF_PASSWORD are set, so this signs in with them rather than ` +
181
+ `through the running agent (account ${agent.account}). Unset them to use the agent.\n`,
182
+ )
183
+ }
184
+ return { agent: null }
185
+ }
186
+ return { agent }
187
+ }
188
+
189
+ // Start the agent as a detached child and hand it the session over stdin.
190
+ async function launchAgent({ session, rootKey, config, idleMs }) {
191
+ const { spawn } = await import('node:child_process')
192
+ const { fileURLToPath } = await import('node:url')
193
+
194
+ // Only what the agent needs to find its home directory and reach the
195
+ // network. Not SF_PASSWORD, not SF_TOTP_CODE, and nothing else the shell
196
+ // happened to export.
197
+ const env = {}
198
+ for (const name of [
199
+ 'PATH', 'HOME', 'USER', 'LOGNAME', 'LANG',
200
+ 'SF_API_BASE_URL', 'SF_SUPABASE_URL', 'SF_SUPABASE_ANON_KEY',
201
+ 'HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'NODE_EXTRA_CA_CERTS',
202
+ ]) {
203
+ if (process.env[name]) env[name] = process.env[name]
204
+ }
205
+
206
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '__agent'], {
207
+ detached: true,
208
+ stdio: ['pipe', 'pipe', 'pipe'],
209
+ env,
210
+ })
211
+
212
+ const ready = await new Promise((resolveReady, reject) => {
213
+ let out = ''
214
+ let err = ''
215
+ const timer = setTimeout(() => {
216
+ child.kill()
217
+ reject(new Error(`The agent did not start within 15 s.${err ? ` ${err.trim()}` : ''}`))
218
+ }, 15_000)
219
+
220
+ child.stdout.setEncoding('utf8')
221
+ child.stderr.setEncoding('utf8')
222
+ child.stdout.on('data', (chunk) => {
223
+ out += chunk
224
+ const newline = out.indexOf('\n')
225
+ if (newline === -1) return
226
+ clearTimeout(timer)
227
+ try {
228
+ resolveReady(JSON.parse(out.slice(0, newline)))
229
+ } catch {
230
+ reject(new Error('The agent sent an unreadable start signal.'))
231
+ }
232
+ })
233
+ child.stderr.on('data', (chunk) => {
234
+ err += chunk
235
+ })
236
+ child.on('exit', (code) => {
237
+ clearTimeout(timer)
238
+ reject(new Error(`The agent exited before it was ready (code ${code}).${err ? ` ${err.trim()}` : ''}`))
239
+ })
240
+
241
+ child.stdin.end(
242
+ JSON.stringify({
243
+ session,
244
+ rootKey: Buffer.from(rootKey).toString('base64'),
245
+ config,
246
+ idleMs,
247
+ }),
248
+ )
249
+ })
250
+
251
+ child.stdout.destroy()
252
+ child.stderr.destroy()
253
+ child.unref()
254
+ return ready
255
+ }
256
+
257
+ function readIdle(flags) {
258
+ if (flags.idle === true) {
259
+ throw new Error('--idle needs a value: sf login --idle=<hours>')
260
+ }
261
+ const hours = flags.idle === undefined ? 8 : Number(flags.idle)
262
+ if (!Number.isFinite(hours) || hours * 60 < 1 || hours > 168) {
263
+ throw new Error('--idle must be a number of hours from 1 minute (0.0167) to 168')
264
+ }
265
+ return { hours, ms: Math.round(hours * 3_600_000) }
266
+ }
267
+
268
+ async function cmdLogin(flags) {
269
+ const idle = readIdle(flags)
270
+
271
+ const existing = await runningAgent()
272
+ if (existing) {
273
+ process.stdout.write(
274
+ `Already logged in (account ${existing.account}, agent pid ${existing.pid}). ` +
275
+ 'Run sf logout first to use another account.\n',
276
+ )
277
+ return
278
+ }
279
+ if (!process.stdin.isTTY) {
280
+ throw new Error(
281
+ 'sf login needs an interactive terminal. It prompts for your password ' +
282
+ 'instead of reading it from the environment.',
283
+ )
284
+ }
285
+
286
+ const cfg = backendConfig()
287
+ const email = process.env.SF_EMAIL || (await promptLine('Email: ')).trim()
288
+ const password = await promptHidden('Password: ')
289
+ const vaultPassword =
290
+ (await promptHidden('Vault password (press Enter if it is the same): ')) || password
291
+
292
+ const { signIn } = await import('./auth.mjs')
293
+ const { fetchAndUnlockVault } = await import('./vault.mjs')
294
+
295
+ process.stderr.write('signing in…\n')
296
+ const session = await signIn({ ...cfg, email, password, getTotpCode: readTotpCode })
297
+
298
+ process.stderr.write('unlocking vault…\n')
299
+ const rootKey = await fetchAndUnlockVault({
300
+ apiBaseUrl: cfg.apiBaseUrl,
301
+ accessToken: session.accessToken,
302
+ password: vaultPassword,
303
+ })
304
+
305
+ const started = await launchAgent({ session, rootKey, config: cfg, idleMs: idle.ms })
306
+ rootKey.fill(0)
307
+
308
+ process.stdout.write(
309
+ `Logged in as ${email}. The agent (pid ${started.pid}) holds the session in memory ` +
310
+ `only and locks after ${idle.hours} h without an upload, sync or verify. ` +
311
+ 'Run sf logout to end it.\n',
312
+ )
313
+ }
314
+
315
+ async function cmdStatus() {
316
+ const status = await runningAgent()
317
+ if (!status) {
318
+ process.stdout.write('Not logged in: no agent is running.\n')
319
+ return
320
+ }
321
+ const totalMinutes = Math.round(status.idleLocksInSec / 60)
322
+ const hours = Math.floor(totalMinutes / 60)
323
+ const minutes = totalMinutes % 60
324
+ process.stdout.write(
325
+ `Logged in (account ${status.account}). Agent pid ${status.pid}; locks after ` +
326
+ `${hours} h ${minutes} min without an upload, sync or verify.\n`,
327
+ )
328
+ }
329
+
330
+ async function cmdLogout(flags) {
331
+ const { AgentUnavailableError, request } = await import('./agent/client.mjs')
332
+ const everywhere = flags.everywhere === true
333
+ let result
334
+ try {
335
+ result = await request('logout', { everywhere }, { timeoutMs: 15_000 })
336
+ } catch (err) {
337
+ if (err instanceof AgentUnavailableError) {
338
+ process.stdout.write('Not logged in: no agent is running.\n')
339
+ return
340
+ }
341
+ throw err
342
+ }
343
+
344
+ if (result.sessionRevoked) {
345
+ process.stdout.write(
346
+ everywhere
347
+ ? 'Logged out. Every ShieldFive session on this account was signed out, including your browser and phone.\n'
348
+ : 'Logged out. The session was revoked on the server.\n',
349
+ )
350
+ return
351
+ }
352
+
353
+ // Both failures leave the key wiped here. They differ in what is known about
354
+ // the session, and in what the user can do about it.
355
+ process.exitCode = 1
356
+ if (result.revokeStatus === 0) {
357
+ process.stdout.write(
358
+ 'Logged out on this machine, but the server could not be reached, so the ' +
359
+ 'session is still valid there. Once you are online, run sf login and then ' +
360
+ 'sf logout --everywhere to end it.\n',
361
+ )
362
+ } else {
363
+ process.stdout.write(
364
+ `Logged out on this machine, but the server did not accept the sign-out ` +
365
+ `(HTTP ${result.revokeStatus}). The session may already have ended. To be ` +
366
+ 'certain, run sf login and then sf logout --everywhere, which ends every ' +
367
+ 'session on this account, including your browser.\n',
368
+ )
369
+ }
370
+ }
371
+
155
372
  // login -> unlock -> encrypt -> upload every file in the folder, once.
156
373
  async function cmdPush(folder) {
374
+ const { agent } = await chooseAuth()
375
+ if (agent) {
376
+ const { request } = await import('./agent/client.mjs')
377
+ process.stderr.write(`pushing to account ${agent.account} through the agent\n`)
378
+ let differs = 0
379
+ for await (const { name, path } of filesIn(resolve(folder))) {
380
+ const result = await request('upload', { path }, { timeoutMs: 0 })
381
+ if (result.matchesFileNow) {
382
+ process.stdout.write(`pushed ${name}\n`)
383
+ } else {
384
+ differs++
385
+ process.stdout.write(
386
+ `pushed ${name}, but it changed while uploading: the vault holds the ` +
387
+ 'version that was read, not the file as it is now\n',
388
+ )
389
+ }
390
+ }
391
+ // Non-zero so a script does not treat a file whose current contents are not
392
+ // in the vault as pushed.
393
+ if (differs) process.exitCode = 2
394
+ return
395
+ }
396
+
157
397
  const cfg = readLiveConfig()
158
398
  const { uploadFile } = await import('./upload.mjs')
159
399
  const { accessToken, rootKey } = await authAndUnlock(cfg)
@@ -171,8 +411,57 @@ async function cmdPush(folder) {
171
411
  }
172
412
  }
173
413
 
414
+ async function syncViaAgent(folder, { watch, intervalMs }, agent) {
415
+ const { AgentUnavailableError, request } = await import('./agent/client.mjs')
416
+ const controller = new AbortController()
417
+ const onSigint = () => {
418
+ process.stderr.write('\nstopping…\n')
419
+ controller.abort()
420
+ }
421
+ if (watch) process.on('SIGINT', onSigint)
422
+ process.stderr.write(`syncing to account ${agent.account} through the agent\n`)
423
+
424
+ try {
425
+ do {
426
+ let summary
427
+ try {
428
+ summary = await request('sync', { folder }, { timeoutMs: 0 })
429
+ } catch (err) {
430
+ if (err instanceof AgentUnavailableError || err.code === 'locked') {
431
+ throw new Error('The agent was locked or logged out. Run sf login to continue.')
432
+ }
433
+ throw err
434
+ }
435
+ for (const e of summary.errors) process.stdout.write(`failed ${e.path}: ${e.message}\n`)
436
+ process.stderr.write(
437
+ `pass: ${summary.uploaded} synced, ${summary.skipped} unchanged` +
438
+ (summary.changed ? `, ${summary.changed} changed while uploading (uploaded again on the next pass)` : '') +
439
+ (summary.failed ? `, ${summary.failed} failed` : '') +
440
+ '\n',
441
+ )
442
+ if (!watch || controller.signal.aborted) break
443
+ await new Promise((r) => {
444
+ const timer = setTimeout(r, intervalMs)
445
+ controller.signal.addEventListener(
446
+ 'abort',
447
+ () => {
448
+ clearTimeout(timer)
449
+ r()
450
+ },
451
+ { once: true },
452
+ )
453
+ })
454
+ } while (!controller.signal.aborted)
455
+ } finally {
456
+ if (watch) process.off('SIGINT', onSigint)
457
+ }
458
+ }
459
+
174
460
  // login -> unlock -> mirror new/changed files into the vault, once or on a loop.
175
461
  async function cmdSync(folder, { watch, intervalMs }) {
462
+ const { agent } = await chooseAuth()
463
+ if (agent) return syncViaAgent(resolve(folder), { watch, intervalMs }, agent)
464
+
176
465
  const cfg = readLiveConfig()
177
466
  const { uploadFile } = await import('./upload.mjs')
178
467
  const { runSync } = await import('./sync.mjs')
@@ -187,6 +476,28 @@ async function cmdSync(folder, { watch, intervalMs }) {
187
476
  })
188
477
  }
189
478
 
479
+ const STATE_LABELS = {
480
+ verified: 'backed up',
481
+ missing: 'NOT confirmed',
482
+ changed_since_upload: 'changed since upload',
483
+ not_in_ledger: 'no upload record',
484
+ unreadable: 'unreadable',
485
+ }
486
+
487
+ async function cmdVerify(paths) {
488
+ if (!paths.length) throw new Error('verify needs at least one file')
489
+ const { request } = await import('./agent/client.mjs')
490
+ const results = await request('verify', { paths: paths.map((p) => resolve(p)) }, { timeoutMs: 0 })
491
+
492
+ for (const r of results) {
493
+ const label = STATE_LABELS[r.state] ?? r.state
494
+ const note = r.matchedPath ? ` (same bytes as ${r.matchedPath})` : r.reason ? ` (${r.reason})` : ''
495
+ process.stdout.write(`${label.padEnd(22)} ${r.path}${note}\n`)
496
+ }
497
+ // Exit 0 only when every file is confirmed, so a script can gate on it.
498
+ if (!results.every((r) => r.state === 'verified')) process.exitCode = 2
499
+ }
500
+
190
501
  // Minimal parse: first non-flag arg after the command is the positional; --flag
191
502
  // and --flag=value are collected. Enough for `sf sync <folder> --watch
192
503
  // --interval=10`.
@@ -211,8 +522,21 @@ async function main() {
211
522
  const { positionals, flags } = parseArgs(argv.slice(1))
212
523
  const folder = positionals[0]
213
524
 
214
- if (!cmd || cmd === '--help' || cmd === '-h') {
525
+ if (cmd === '__agent') {
526
+ // A detached agent outlives the terminal that started it; writing to a
527
+ // closed pipe must not take it down.
528
+ process.stdout.on('error', () => {})
529
+ process.stderr.on('error', () => {})
530
+ const { runAgent } = await import('./agent/main.mjs')
531
+ await runAgent()
532
+ } else if (!cmd || cmd === '--help' || cmd === '-h') {
215
533
  usage()
534
+ } else if (cmd === 'login') {
535
+ await cmdLogin(flags)
536
+ } else if (cmd === 'status') {
537
+ await cmdStatus()
538
+ } else if (cmd === 'logout') {
539
+ await cmdLogout(flags)
216
540
  } else if (cmd === 'encrypt') {
217
541
  if (!folder) throw new Error('encrypt needs a <folder>')
218
542
  await cmdEncrypt(folder)
@@ -221,6 +545,9 @@ async function main() {
221
545
  await cmdPush(folder)
222
546
  } else if (cmd === 'sync') {
223
547
  if (!folder) throw new Error('sync needs a <folder>')
548
+ // `--interval 10` (space-separated) would otherwise parse as a bare flag and
549
+ // quietly become a one-second interval.
550
+ if (flags.interval === true) throw new Error('--interval needs a value: --interval=<seconds>')
224
551
  const intervalSec = flags.interval ? Number(flags.interval) : 5
225
552
  if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
226
553
  throw new Error('--interval must be a positive number of seconds')
@@ -229,6 +556,8 @@ async function main() {
229
556
  watch: Boolean(flags.watch),
230
557
  intervalMs: Math.round(intervalSec * 1000),
231
558
  })
559
+ } else if (cmd === 'verify') {
560
+ await cmdVerify(positionals)
232
561
  } else {
233
562
  usage()
234
563
  process.exitCode = 1
package/src/prompt.mjs ADDED
@@ -0,0 +1,79 @@
1
+ // ShieldFive CLI — terminal prompts.
2
+ //
3
+ // The password prompt reads in raw mode and echoes nothing, not even asterisks:
4
+ // a count of characters is a fact about the password. There is deliberately no
5
+ // way to pass a password on the command line, where it would sit in shell
6
+ // history and in every process listing on the machine.
7
+
8
+ import { createInterface } from 'node:readline'
9
+
10
+ // Written as escapes on purpose. Literal control characters in source are
11
+ // invisible in review and easy to lose in an editor; a prompt that silently
12
+ // stopped matching Ctrl-C would trap the user in raw mode.
13
+ const CTRL_C = '\u0003'
14
+ const CTRL_D = '\u0004'
15
+ const BACKSPACE = '\u007f'
16
+ const CTRL_H = '\b'
17
+
18
+ /** Prompt for a single visible line (an email address, a TOTP code). */
19
+ export function promptLine(question, { input = process.stdin, output = process.stderr } = {}) {
20
+ return new Promise((resolve, reject) => {
21
+ const rl = createInterface({ input, output })
22
+ rl.question(question, (answer) => {
23
+ rl.close()
24
+ resolve(answer)
25
+ })
26
+ rl.on('error', reject)
27
+ })
28
+ }
29
+
30
+ /** Prompt for a secret without echoing it. Needs a terminal. */
31
+ export function promptHidden(question, { input = process.stdin, output = process.stderr } = {}) {
32
+ if (!input.isTTY || typeof input.setRawMode !== 'function') {
33
+ return Promise.reject(
34
+ new Error(
35
+ 'A password prompt needs a terminal. Run sf login in an interactive ' +
36
+ 'shell; it cannot read a password from a pipe.',
37
+ ),
38
+ )
39
+ }
40
+
41
+ return new Promise((resolve, reject) => {
42
+ const wasRaw = Boolean(input.isRaw)
43
+ let value = ''
44
+
45
+ const finish = (err) => {
46
+ input.off('data', onData)
47
+ input.setRawMode(wasRaw)
48
+ input.pause()
49
+ output.write('\n')
50
+ if (err) reject(err)
51
+ else resolve(value)
52
+ }
53
+
54
+ const onData = (chunk) => {
55
+ for (const ch of String(chunk)) {
56
+ if (ch === '\r' || ch === '\n') return finish()
57
+ if (ch === CTRL_C) return finish(new Error('Cancelled.'))
58
+ if (ch === CTRL_D) {
59
+ if (!value) return finish(new Error('Cancelled.'))
60
+ continue
61
+ }
62
+ if (ch === BACKSPACE || ch === CTRL_H) {
63
+ value = value.slice(0, -1)
64
+ continue
65
+ }
66
+ // Other control characters, including the escape sequences arrow keys
67
+ // send, are not part of a password.
68
+ if (ch < ' ') continue
69
+ value += ch
70
+ }
71
+ }
72
+
73
+ output.write(question)
74
+ input.setEncoding('utf8')
75
+ input.setRawMode(true)
76
+ input.resume()
77
+ input.on('data', onData)
78
+ })
79
+ }