diff --git a/packages/appstash/README.md b/packages/appstash/README.md index b44077a..bf70588 100644 --- a/packages/appstash/README.md +++ b/packages/appstash/README.md @@ -262,6 +262,14 @@ Every file it writes is atomic (temp file + `rename`) and mode `0600`. A stored that exists but does not parse throws with its path — it is never silently replaced with defaults. +The directories appstash creates are mode `0700`, and the store sets the ones it owns +to `0700` when it opens, so a store that a group shared through its directory modes +is private to its owner from then on. A context name becomes a file name, so every +method that takes one throws for a name that could reach a file outside the store: +an empty name, `.`, `..`, or a name with `/`, `\` or a NUL character. Any other name +works. `assertContextName(name)` runs the same check, for a caller that wants to fail +before it touches the store. + ### One signed-in state across several tools Pass `stashName` when multiple binaries are really one product. They then share diff --git a/packages/appstash/__tests__/config-store.test.ts b/packages/appstash/__tests__/config-store.test.ts index 1613172..ae084af 100644 --- a/packages/appstash/__tests__/config-store.test.ts +++ b/packages/appstash/__tests__/config-store.test.ts @@ -2,7 +2,7 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { createConfigStore } from '../src'; +import { appstash, createConfigStore } from '../src'; describe('createConfigStore', () => { let tempBase: string; @@ -614,4 +614,126 @@ describe('createConfigStore', () => { expect(store.getCurrentContext()).toBeNull(); }); }); + + describe('context names', () => { + const configDir = () => appstash('testapp', { baseDir: tempBase }).config; + const contextsDir = () => path.join(configDir(), 'contexts'); + + it('refuses a name that would overwrite settings.json', () => { + const store = createStore(); + store.saveSettings({ currentContext: 'production' }); + expect(() => store.createContext('../settings', { endpoint: 'https://evil.example.com' })).toThrow('"../settings" is not a valid context name'); + expect(store.loadSettings()).toEqual({ currentContext: 'production' }); + }); + + it.each([ + ['../../../victim', () => path.join(contextsDir(), '../../../victim.json')], + ['../credentials', () => path.join(configDir(), 'credentials.json')] + ])('refuses to delete the file %s names', (name, target) => { + const store = createStore(); + store.setCredentials('production', { token: 'keep-me' }); + fs.mkdirSync(path.dirname(target()), { recursive: true }); + if (!fs.existsSync(target())) fs.writeFileSync(target(), '{}'); + expect(() => store.deleteContext(name)).toThrow('is not a valid context name'); + expect(fs.existsSync(target())).toBe(true); + expect(store.getCredentials('production')).toMatchObject({ token: 'keep-me' }); + }); + + it('refuses to read credentials.json as a context', () => { + const store = createStore(); + store.setCredentials('production', { token: 'keep-me' }); + expect(() => store.loadContext('../credentials')).toThrow('is not a valid context name'); + expect(() => store.setCurrentContext('../credentials')).toThrow('is not a valid context name'); + }); + + const requiredNameCalls = (store: ReturnType, name: string): Array<() => unknown> => [ + () => store.createContext(name, { endpoint: 'https://api.example.com' }), + () => store.loadContext(name), + () => store.deleteContext(name), + () => store.setCurrentContext(name), + () => store.setCredentials(name, { token: 't' }), + () => store.getCredentials(name), + () => store.removeCredentials(name), + () => store.hasValidCredentials(name) + ]; + + it.each(['.', '..', 'a/b', 'a\\b', 'a\0b'])('refuses %j in every method that takes a context name', (name) => { + const store = createStore(); + const calls = [ + ...requiredNameCalls(store, name), + () => store.setVar('k', 'v', name), + () => store.getVar('k', name), + () => store.listVars(name) + ]; + for (const call of calls) expect(call).toThrow('is not a valid context name'); + }); + + it('refuses an empty name in every method that requires a name', () => { + const store = createStore(); + for (const call of requiredNameCalls(store, '')) expect(call).toThrow('is not a valid context name'); + }); + + it.each(['my app', 'prod:eu', 'user@example.com', `${'o'.repeat(30)}%2F${'r'.repeat(80)}`])( + 'keeps %j working for write, read and delete', + (name) => { + const store = createStore(); + store.createContext(name, { endpoint: 'https://api.example.com' }); + store.setCurrentContext(name); + store.setCredentials(name, { token: 't' }); + store.setVar('k', 'v', name); + expect(store.getCurrentContext()).toMatchObject({ name, endpoint: 'https://api.example.com' }); + expect(store.getCredentials(name)).toMatchObject({ token: 't' }); + expect(store.getVar('k')).toBe('v'); + expect(store.removeCredentials(name)).toBe(true); + expect(store.deleteContext(name)).toBe(true); + expect(store.listContexts()).toEqual([]); + } + ); + + it.each(['__proto__', 'constructor', 'toString', 'hasOwnProperty'])('keeps %j as a plain key, never a member of Object.prototype', (name) => { + const store = createStore(); + store.createContext('production', { endpoint: 'https://api.example.com', targets: { admin: { endpoint: 'https://admin.example.com' } } }); + expect(store.getCredentials(name)).toBeNull(); + expect(store.removeCredentials(name)).toBe(false); + expect(store.getVar(name, 'production')).toBeNull(); + expect(store.deleteVar(name, 'production')).toBe(false); + expect(store.getTargetEndpoint(name, 'production')).toBe('https://api.example.com'); + store.setCredentials(name, { token: 't' }); + store.setVar(name, 'v', 'production'); + + const reopened = createStore(); + expect(reopened.getCredentials(name)).toMatchObject({ token: 't' }); + expect(reopened.getVar(name, 'production')).toBe('v'); + expect(Object.entries(reopened.listVars('production'))).toEqual([[name, 'v']]); + expect(reopened.removeCredentials(name)).toBe(true); + expect(reopened.getCredentials(name)).toBeNull(); + }); + }); + + describe('directory modes', () => { + const posix = process.platform !== 'win32'; + const mode = (dir: string) => fs.statSync(dir).mode & 0o777; + const owned = () => { + const dirs = appstash('testapp', { baseDir: tempBase }); + return [dirs.root, dirs.config, dirs.cache, dirs.data, dirs.logs, path.join(dirs.config, 'contexts'), path.join(dirs.config, 'vars')]; + }; + + (posix ? it : it.skip)('creates every directory it owns with mode 0700', () => { + const store = createStore(); + store.createContext('production', { endpoint: 'https://api.example.com' }); + store.setVar('k', 'v', 'production'); + expect(owned().map(mode)).toEqual(owned().map(() => 0o700)); + }); + + (posix ? it : it.skip)('tightens the directories it owns when it opens, and never the base directory it was given', () => { + fs.chmodSync(tempBase, 0o755); + for (const dir of owned()) { + fs.mkdirSync(dir, { recursive: true }); + fs.chmodSync(dir, 0o755); + } + createStore(); + expect(owned().map(mode)).toEqual(owned().map(() => 0o700)); + expect(mode(tempBase)).toBe(0o755); + }); + }); }); diff --git a/packages/appstash/src/config-store.ts b/packages/appstash/src/config-store.ts index e0ceaad..f5ed05c 100644 --- a/packages/appstash/src/config-store.ts +++ b/packages/appstash/src/config-store.ts @@ -1,7 +1,7 @@ import * as fs from 'fs'; import * as path from 'path'; -import { appstash, resolve } from './index'; +import { appstash, DIRECTORY_MODE, resolve } from './index'; export interface ContextTargetEndpoint { endpoint: string; @@ -131,7 +131,7 @@ function readJson(filePath: string, fallback: T): T { */ function writeJson(filePath: string, data: unknown, mode = 0o600): void { const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true }); + fs.mkdirSync(dir, { recursive: true, mode: DIRECTORY_MODE }); const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.tmp`); try { fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode }); @@ -146,11 +146,38 @@ function writeJson(filePath: string, data: unknown, mode = 0o600): void { } } +// `\` separates paths on Windows; NUL ends a path in the system calls. +const PATH_CHARACTERS = ['/', '\\', '\0']; + +/** + * Throws when `name` could reach a file outside the store's directory, because a context name becomes part of a + * file path. Any other name is the caller's choice. + */ +export function assertContextName(name: string): void { + if (typeof name === 'string' && name !== '' && name !== '.' && name !== '..' && !PATH_CHARACTERS.some((c) => name.includes(c))) return; + const shown = typeof name === 'string' && name.length > 100 ? `${name.slice(0, 100)}...` : name; + throw new Error( + `${JSON.stringify(shown)} is not a valid context name, because a context name becomes a file name in the store. ` + + 'Use a name that is not empty, is not "." or "..", and has no "/", "\\" or NUL character.' + ); +} + +const ownValue = (map: Record, key: string): T | undefined => + Object.hasOwn(map, key) ? map[key] : undefined; + +/** A map the store writes by a caller's key; with no prototype, a key such as `__proto__` is a plain entry. */ +const keyedMap = (entries: Record): Record => Object.assign(Object.create(null), entries); + export function createConfigStore(toolName: string, options?: ConfigStoreOptions): ConfigStore { const stashName = options?.stashName ?? toolName; const codec = options?.codec; const codecName = codec?.name ?? PLAINTEXT_CODEC; const dirs = appstash(stashName, { ensure: true, baseDir: options?.baseDir }); + // Directories that already exist may be readable by others; tighten only the ones this store owns. + const owned = [dirs.root, dirs.config, dirs.cache, dirs.data, dirs.logs, resolve(dirs, 'config', 'contexts'), resolve(dirs, 'config', 'vars')]; + for (const dir of owned) { + if (fs.existsSync(dir) && (fs.statSync(dir).mode & 0o777) !== DIRECTORY_MODE) fs.chmodSync(dir, DIRECTORY_MODE); + } function settingsPath(): string { return resolve(dirs, 'config', 'settings.json'); @@ -161,9 +188,10 @@ export function createConfigStore(toolName: string, options?: ConfigStoreOptions } function contextPath(name: string): string { + assertContextName(name); const contextsDir = resolve(dirs, 'config', 'contexts'); if (!fs.existsSync(contextsDir)) { - fs.mkdirSync(contextsDir, { recursive: true }); + fs.mkdirSync(contextsDir, { recursive: true, mode: DIRECTORY_MODE }); } return path.join(contextsDir, `${name}.json`); } @@ -256,6 +284,7 @@ export function createConfigStore(toolName: string, options?: ConfigStoreOptions /** Stored credentials, still encoded. */ function loadCredentials(): Credentials { const credentials = readJson(credentialsPath(), { tokens: {} }); + credentials.tokens = keyedMap(credentials.tokens); const fileCodec = credentials.codec ?? PLAINTEXT_CODEC; if (Object.keys(credentials.tokens).length > 0 && fileCodec !== codecName) { throw new Error( @@ -271,21 +300,24 @@ export function createConfigStore(toolName: string, options?: ConfigStoreOptions } function setCredentials(contextName: string, creds: ContextCredentials): void { + assertContextName(contextName); const credentials = loadCredentials(); credentials.tokens[contextName] = codec ? mapSecrets(creds, codec.encode) : creds; saveCredentials(credentials); } function getCredentials(contextName: string): ContextCredentials | null { + assertContextName(contextName); const credentials = loadCredentials(); - const stored = credentials.tokens[contextName]; + const stored = ownValue(credentials.tokens, contextName); if (!stored) return null; return codec ? mapSecrets(stored, codec.decode) : stored; } function removeCredentials(contextName: string): boolean { + assertContextName(contextName); const credentials = loadCredentials(); - if (credentials.tokens[contextName]) { + if (ownValue(credentials.tokens, contextName)) { delete credentials.tokens[contextName]; saveCredentials(credentials); return true; @@ -315,22 +347,21 @@ export function createConfigStore(toolName: string, options?: ConfigStoreOptions ctx = getCurrentContext(); } if (!ctx) return null; - if (ctx.targets && ctx.targets[targetName]) { - return ctx.targets[targetName].endpoint; - } - return ctx.endpoint; + const target = ctx.targets && ownValue(ctx.targets, targetName); + return target ? target.endpoint : ctx.endpoint; } function varsPath(ctxName: string): string { + assertContextName(ctxName); const varsDir = resolve(dirs, 'config', 'vars'); if (!fs.existsSync(varsDir)) { - fs.mkdirSync(varsDir, { recursive: true }); + fs.mkdirSync(varsDir, { recursive: true, mode: DIRECTORY_MODE }); } return path.join(varsDir, `${ctxName}.json`); } function loadVars(ctxName: string): Record { - return readJson>(varsPath(ctxName), {}); + return keyedMap(readJson>(varsPath(ctxName), {})); } function saveVars(ctxName: string, vars: Record): void { @@ -338,7 +369,10 @@ export function createConfigStore(toolName: string, options?: ConfigStoreOptions } function resolveContextName(contextName?: string): string | null { - if (contextName) return contextName; + if (contextName) { + assertContextName(contextName); + return contextName; + } const settings = loadSettings(); return settings.currentContext || null; } @@ -357,14 +391,14 @@ export function createConfigStore(toolName: string, options?: ConfigStoreOptions const ctxName = resolveContextName(contextName); if (!ctxName) return null; const vars = loadVars(ctxName); - return vars[key] ?? null; + return ownValue(vars, key) ?? null; } function deleteVar(key: string, contextName?: string): boolean { const ctxName = resolveContextName(contextName); if (!ctxName) return false; const vars = loadVars(ctxName); - if (key in vars) { + if (Object.hasOwn(vars, key)) { delete vars[key]; saveVars(ctxName, vars); return true; @@ -375,7 +409,7 @@ export function createConfigStore(toolName: string, options?: ConfigStoreOptions function listVars(contextName?: string): Record { const ctxName = resolveContextName(contextName); if (!ctxName) return {}; - return loadVars(ctxName); + return { ...loadVars(ctxName) }; } function getClientConfig(targetName: string, contextName?: string): ClientConfig { diff --git a/packages/appstash/src/index.ts b/packages/appstash/src/index.ts index d3821ee..93127d8 100644 --- a/packages/appstash/src/index.ts +++ b/packages/appstash/src/index.ts @@ -192,6 +192,9 @@ export function ensure(dirs: AppStashResult): EnsureResult { return ensureDirectories(dirs); } +/** Directories appstash creates are private to the user, as the XDG base directory spec asks. */ +export const DIRECTORY_MODE = 0o700; + /** * Internal function to ensure directories exist */ @@ -209,7 +212,7 @@ function ensureDirectories( for (const dir of persistentDirs) { try { if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); + fs.mkdirSync(dir, { recursive: true, mode: DIRECTORY_MODE }); created.push(dir); } } catch { @@ -231,7 +234,7 @@ function ensureDirectories( for (const dir of xdgDirs) { try { if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); + fs.mkdirSync(dir, { recursive: true, mode: DIRECTORY_MODE }); created.push(dir); } } catch { @@ -287,4 +290,4 @@ export type { GlobalSettings, SecretCodec, } from './config-store'; -export { createConfigStore } from './config-store'; +export { assertContextName, createConfigStore } from './config-store'; diff --git a/packages/inquirerer-utils/__tests__/update-check.test.ts b/packages/inquirerer-utils/__tests__/update-check.test.ts new file mode 100644 index 0000000..30d0862 --- /dev/null +++ b/packages/inquirerer-utils/__tests__/update-check.test.ts @@ -0,0 +1,54 @@ +import { appstash } from 'appstash'; +import * as fs from 'fs'; +import * as http from 'http'; +import { AddressInfo } from 'net'; +import * as os from 'os'; +import * as path from 'path'; + +import { checkForUpdates, suppressUpdateCheck } from '../src'; + +const posix = process.platform !== 'win32'; +const mode = (dir: string): number => fs.statSync(dir).mode & 0o777; + +describe('the directories the update check creates', () => { + let server: http.Server; + let registry: string; + let base: string; + const savedBase = process.env.APPSTASH_BASE_DIR; + + beforeAll(async () => { + server = http.createServer((_request, response) => { + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify({ version: '9.9.9' })); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + registry = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + }); + + afterAll(() => new Promise((resolve) => server.close(() => resolve()))); + + beforeEach(() => { + base = fs.mkdtempSync(path.join(os.tmpdir(), 'inquirerer-utils-update-')); + process.env.APPSTASH_BASE_DIR = base; + }); + + afterEach(() => { + if (savedBase === undefined) delete process.env.APPSTASH_BASE_DIR; + else process.env.APPSTASH_BASE_DIR = savedBase; + fs.rmSync(base, { recursive: true, force: true }); + }); + + const check = () => checkForUpdates({ pkgName: 'demo-cli', pkgVersion: '1.0.0', toolName: 'demo', registryBaseUrl: registry, force: true }); + const dirs = () => appstash('demo', { baseDir: base }); + + (posix ? it.each : it.skip.each)([ + ['the update check', async () => { await check(); }], + ['suppressUpdateCheck', async () => { suppressUpdateCheck('demo', '1.0.0'); }] + ])('%s creates only the cache directory, with the tool directory, at mode 0700', async (_caller, run) => { + await run(); + const { root, cache } = dirs(); + expect(fs.existsSync(path.join(cache, 'update-check.json'))).toBe(true); + expect(fs.readdirSync(root)).toEqual(['cache']); + expect([mode(root), mode(cache)]).toEqual([0o700, 0o700]); + }); +}); diff --git a/packages/inquirerer-utils/src/update-check.ts b/packages/inquirerer-utils/src/update-check.ts index 79a4d6d..fca7f67 100644 --- a/packages/inquirerer-utils/src/update-check.ts +++ b/packages/inquirerer-utils/src/update-check.ts @@ -1,4 +1,4 @@ -import { appstash } from 'appstash'; +import { appstash, DIRECTORY_MODE } from 'appstash'; import * as fs from 'fs'; import * as path from 'path'; import semver from 'semver'; @@ -108,7 +108,7 @@ export function suppressUpdateCheck(toolName: string, currentVersion: string): b const dirs = appstash(toolName); const cacheFile = path.join(dirs.cache, CACHE_FILENAME); if (!fs.existsSync(dirs.cache)) { - fs.mkdirSync(dirs.cache, { recursive: true }); + fs.mkdirSync(dirs.cache, { recursive: true, mode: DIRECTORY_MODE }); } fs.writeFileSync(cacheFile, JSON.stringify({ latestVersion: currentVersion, @@ -207,7 +207,7 @@ export const checkForUpdates = async ( // Cache the result try { if (!fs.existsSync(dirs.cache)) { - fs.mkdirSync(dirs.cache, { recursive: true }); + fs.mkdirSync(dirs.cache, { recursive: true, mode: DIRECTORY_MODE }); } fs.writeFileSync(cacheFile, JSON.stringify({ latestVersion, diff --git a/packages/inquirerer/README.md b/packages/inquirerer/README.md index 0679bf2..13c4924 100644 --- a/packages/inquirerer/README.md +++ b/packages/inquirerer/README.md @@ -223,11 +223,29 @@ interface InquirererOptions { globalMaxLines?: number; // Max lines for list displays (default: 10) mutateArgs?: boolean; // Mutate argv object (default: true) resolverRegistry?: DefaultResolverRegistry; // Custom resolver registry + clearScreen?: boolean; // Reset the terminal before each prompt (default: true) + onCancel?: (reason: CancelReason) => Error; // Reject a prompt that ends without an answer (default: unset) } const prompter = new Inquirerer(options); ``` +`clearScreen: false` keeps what is already on the screen: each prompt is written below it, and a prompt that redraws itself erases only the lines it drew. + +By default, Ctrl-C at a prompt exits the process with code 0. With `onCancel`, a prompt that ends without an answer rejects with the error `onCancel` returns, so the caller's `finally` blocks run. The `CancelReason` is `'interrupt'` for Ctrl-C, or `'end-of-input'` for Ctrl-D or a closed input stream. Ctrl-C while no prompt is pending sends SIGINT to the process. After a cancelled prompt, call `close()` on the prompter and do not prompt with it again. + +```typescript +const prompter = new Inquirerer({ + clearScreen: false, + onCancel: (reason) => new Error(reason === 'interrupt' ? 'Cancelled (Ctrl-C).' : 'The input ended before an answer.') +}); +try { + await prompter.prompt({}, questions); +} finally { + prompter.close(); +} +``` + #### Methods ```typescript diff --git a/packages/inquirerer/__tests__/password-prompt.test.ts b/packages/inquirerer/__tests__/password-prompt.test.ts new file mode 100644 index 0000000..77c5da6 --- /dev/null +++ b/packages/inquirerer/__tests__/password-prompt.test.ts @@ -0,0 +1,65 @@ +import { stripAnsi } from 'clean-ansi'; +import { PassThrough, Writable } from 'stream'; + +import { Inquirerer } from '../src'; + +/** A fake terminal: readline sees a TTY on both ends, so it runs in terminal mode and echoes what it reads. */ +function terminal() { + const input = new PassThrough(); + Object.assign(input, { isTTY: true, setRawMode: () => input }); + let raw = ''; + const output = new Writable({ + write(chunk, _encoding, callback) { + raw += chunk.toString(); + callback(); + } + }); + Object.assign(output, { isTTY: true, columns: 80, rows: 24 }); + return { input, output, raw: () => raw, text: () => stripAnsi(raw) }; +} + +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +async function type(input: PassThrough, keys: string[]): Promise { + for (const key of keys) { + input.write(key); + await tick(); + } +} + +describe('the password prompt', () => { + it('never writes the typed characters, keeps every code point, and handles backspace and paste', async () => { + const term = terminal(); + const prompter = new Inquirerer({ input: term.input, output: term.output }); + const answers = prompter.prompt({}, [{ type: 'password', name: 'pw', message: 'Enter it', required: true }]); + await tick(); + await type(term.input, ['q', 'ä', '€', '9', '😀', '\x7f', 'Ω', 'zz42', '\r']); + expect(await answers).toEqual({ pw: 'qä€9Ωzz42' }); + prompter.close(); + + const shown = term.text(); + for (const char of ['q', 'ä', '€', '9', '😀', 'Ω', 'z', '4', '2']) expect(shown).not.toContain(char); + expect(shown).toContain(`> ${'*'.repeat(9)}`); + // With the default clearScreen, the screen is reset before the prompt draws, as for every other prompt. + expect(term.raw().split('\x1bc').length - 1).toBe(1); + expect(term.raw().indexOf('\x1bc')).toBeLessThan(term.raw().indexOf('Enter it')); + }); + + it('with onCancel set, returns the secret, and the next prompt still ends as cancelled on Ctrl-D', async () => { + const term = terminal(); + const prompter = new Inquirerer({ input: term.input, output: term.output, onCancel: (reason) => new Error(reason) }); + const outcomeOf = (answers: Promise) => + Promise.race([answers.catch((error: unknown) => error), new Promise((resolve) => setTimeout(() => resolve('still waiting'), 200))]); + + const secret = outcomeOf(prompter.prompt({}, [{ type: 'password', name: 'pw', message: 'Enter it', required: true }])); + await tick(); + await type(term.input, ['s3cret', '\r']); + expect(await secret).toEqual({ pw: 's3cret' }); + + const next = outcomeOf(prompter.prompt({}, [{ type: 'text', name: 'name', message: 'Name' }])); + await tick(); + await type(term.input, ['\x04']); + expect(await next).toEqual(new Error('end-of-input')); + prompter.close(); + }); +}); diff --git a/packages/inquirerer/__tests__/prompt-options.test.ts b/packages/inquirerer/__tests__/prompt-options.test.ts new file mode 100644 index 0000000..83e9366 --- /dev/null +++ b/packages/inquirerer/__tests__/prompt-options.test.ts @@ -0,0 +1,118 @@ +import { PassThrough, Writable } from 'stream'; + +import { CancelReason, Inquirerer } from '../src'; +import { Question } from '../src/question'; + +/** A fake terminal: readline sees a TTY on both ends, so it runs in terminal mode as it does for a person. */ +function terminal() { + const input = new PassThrough(); + Object.assign(input, { isTTY: true, setRawMode: () => input }); + let raw = ''; + const output = new Writable({ + write(chunk, _encoding, callback) { + raw += chunk.toString(); + callback(); + } + }); + Object.assign(output, { isTTY: true, columns: 80, rows: 24 }); + return { input, output, raw: () => raw }; +} + +const tick = () => new Promise((resolve) => setImmediate(resolve)); +const STILL_WAITING = 'still waiting'; +/** The prompt's answer or its error, or STILL_WAITING when it has neither after 200 ms. */ +const outcomeOf = (answers: Promise) => + Promise.race([answers.catch((error: unknown) => error), new Promise((resolve) => setTimeout(() => resolve(STILL_WAITING), 200))]); + +async function type(input: PassThrough, keys: string[]): Promise { + for (const key of keys) { + input.write(key); + await tick(); + } +} + +class Cancelled extends Error { + constructor(readonly reason: CancelReason) { + super(`cancelled: ${reason}`); + } +} + +const list: Question = { type: 'list', name: 'pick', message: 'Pick one', options: ['a', 'b', 'c'] }; +const text: Question = { type: 'text', name: 'name', message: 'Name' }; + +describe('the clearScreen option', () => { + it('false writes each prompt below the screen, and a redraw erases only the lines the prompt drew', async () => { + const term = terminal(); + term.output.write('earlier output\n'); + const prompter = new Inquirerer({ input: term.input, output: term.output, clearScreen: false }); + const answers = prompter.prompt({}, [list]); + await tick(); + await type(term.input, ['\u001b[B', '\u001b[B', '\r']); + expect(await answers).toEqual({ pick: 'c' }); + prompter.close(); + + const raw = term.raw(); + expect(raw).not.toContain('\x1bc'); + expect(raw.startsWith('earlier output\n')).toBe(true); + const parts = raw.slice('earlier output\n'.length).split(/\x1b\[(\d+)A\r\x1b\[J/); + const erased = parts.filter((_, i) => i % 2 === 1).map(Number); + const drawn = parts.filter((_, i) => i % 2 === 0).slice(0, -1).map((part) => part.split('\n').length - 1); + expect(erased.length).toBeGreaterThanOrEqual(2); + expect(erased).toEqual(drawn); + }); +}); + +describe('the onCancel option', () => { + let exit: jest.SpyInstance; + let kill: jest.SpyInstance; + + beforeEach(() => { + exit = jest.spyOn(process, 'exit').mockImplementation((): never => undefined as never); + kill = jest.spyOn(process, 'kill').mockImplementation(() => true); + }); + + afterEach(() => { + exit.mockRestore(); + kill.mockRestore(); + }); + + it.each<[string, Question[], string[], CancelReason]>([ + ['Ctrl-C at a list prompt', [list], ['\x03'], 'interrupt'], + ['Ctrl-D at a list prompt', [list], ['\x04'], 'end-of-input'], + ['Ctrl-C at a text prompt after a list prompt', [list, text], ['\r', '\x03'], 'interrupt'], + ['Ctrl-D at a text prompt after a list prompt', [list, text], ['\r', '\x04'], 'end-of-input'] + ])('%s rejects the prompt with the onCancel error', async (_case, questions, keys, reason) => { + const term = terminal(); + const prompter = new Inquirerer({ input: term.input, output: term.output, onCancel: (why) => new Cancelled(why) }); + const outcome = outcomeOf(prompter.prompt({}, questions)); + await tick(); + await type(term.input, keys); + expect(await outcome).toEqual(new Cancelled(reason)); + prompter.close(); + expect(exit).not.toHaveBeenCalled(); + expect(kill).not.toHaveBeenCalled(); + }); + + it('rejects a waiting prompt with end-of-input when the input stream ends', async () => { + const term = terminal(); + const prompter = new Inquirerer({ input: term.input, output: term.output, onCancel: (why) => new Cancelled(why) }); + const outcome = outcomeOf(prompter.prompt({}, [text])); + await tick(); + term.input.end(); + expect(await outcome).toEqual(new Cancelled('end-of-input')); + prompter.close(); + }); + + it('sends SIGINT to the process for Ctrl-C while no prompt is pending', async () => { + const term = terminal(); + const prompter = new Inquirerer({ input: term.input, output: term.output, onCancel: (why) => new Cancelled(why) }); + const answers = prompter.prompt({}, [list]); + await tick(); + await type(term.input, ['\r']); + expect(await answers).toEqual({ pick: 'a' }); + await type(term.input, ['\x03']); + prompter.close(); + expect(kill).toHaveBeenCalledWith(process.pid, 'SIGINT'); + expect(exit).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/inquirerer/src/index.ts b/packages/inquirerer/src/index.ts index 7857cb3..c066cf6 100644 --- a/packages/inquirerer/src/index.ts +++ b/packages/inquirerer/src/index.ts @@ -1,4 +1,5 @@ export * from './commander'; +export type { CancelReason } from './keypress'; export * from './prompt'; export * from './question'; export * from './resolvers'; diff --git a/packages/inquirerer/src/keypress.ts b/packages/inquirerer/src/keypress.ts index 3475263..9676bb4 100644 --- a/packages/inquirerer/src/keypress.ts +++ b/packages/inquirerer/src/keypress.ts @@ -122,6 +122,9 @@ export function segmentKeys(chunk: string): string[] { return keys; } +/** Why a prompt ended without an answer: Ctrl-C, or the end of input (Ctrl-D, or a closed stdin). */ +export type CancelReason = 'interrupt' | 'end-of-input'; + /** * Handles keyboard input for interactive prompts. * @@ -135,6 +138,8 @@ export function segmentKeys(chunk: string): string[] { */ export class TerminalKeypress { private listeners: Record = {}; + private unhandled: ((key: string) => void) | null = null; + private cancelKey: ((reason: CancelReason) => void) | null = null; private active: boolean = true; private noTty: boolean; private input: Readable; @@ -163,7 +168,11 @@ export class TerminalKeypress { private setupListeners(): void { this.dataHandler = (chunk: string) => { - if (!this.active) return; + if (!this.active) { + // A cancel-key handler hears Ctrl-C also while no prompt reads keys. + if (this.cancelKey && chunk.includes(KEY_CODES.CTRL_C)) this.cancelKey('interrupt'); + return; + } // A chunk carrying several keypresses (paste, fast typing) matches no // single registered key, so dispatch it key by key. An exact match wins // first: consumers may register sequences the segmenter does not know. @@ -181,12 +190,22 @@ export class TerminalKeypress { if (handlers) { // Copy: a handler may register or remove handlers for the same key. for (const handler of [...handlers]) handler(); + } else { + this.unhandled?.(key); } if (key === KEY_CODES.CTRL_C) { - this.proc.exit(0); + if (this.cancelKey) this.cancelKey('interrupt'); + else this.proc.exit(0); + } else if (key === KEY_CODES.CTRL_D) { + this.cancelKey?.('end-of-input'); } } + /** Ctrl-C calls this with 'interrupt' in place of exiting the process, and Ctrl-D with 'end-of-input'. */ + onCancelKey(callback: (reason: CancelReason) => void): void { + this.cancelKey = callback; + } + on(key: string, callback: KeyHandler): void { if (!this.listeners[key]) { this.listeners[key] = []; @@ -203,8 +222,14 @@ export class TerminalKeypress { } } + /** Receives each key that has no handler of its own, for example any typed character. */ + onUnhandled(callback: (key: string) => void): void { + this.unhandled = callback; + } + clearHandlers(): void { this.listeners = {}; + this.unhandled = null; } pause(): void { diff --git a/packages/inquirerer/src/prompt.ts b/packages/inquirerer/src/prompt.ts index 8a2d37b..cf41e5c 100644 --- a/packages/inquirerer/src/prompt.ts +++ b/packages/inquirerer/src/prompt.ts @@ -2,7 +2,7 @@ import readline from 'readline'; import { Readable, Writable } from 'stream'; import { blue, dim, gray, red, white, whiteBright, yellow } from 'yanse'; -import { KEY_CODES, TerminalKeypress } from './keypress'; +import { CancelReason, KEY_CODES, TerminalKeypress } from './keypress'; import { AutocompleteQuestion, CheckboxQuestion, ConfirmQuestion, JsonQuestion, ListQuestion, NumberQuestion, OptionValue, PasswordQuestion, Question, TextQuestion, Validation } from './question'; import { DefaultResolverRegistry, globalResolverRegistry } from './resolvers'; // import { writeFileSync } from 'fs'; @@ -212,7 +212,21 @@ export interface InquirererOptions { mutateArgs?: boolean; resolverRegistry?: DefaultResolverRegistry; timeout?: number; + /** + * True (the default) resets the terminal (ESC c) before each prompt. False keeps what is on the screen: + * a prompt is written below it, and a prompt that redraws erases only its own last drawing. + */ + clearScreen?: boolean; + /** + * When set, a prompt that ends without an answer rejects with the returned error: Ctrl-C ('interrupt', in place + * of exiting the process), or the end of input ('end-of-input': Ctrl-D, or a closed stdin). Ctrl-C while no + * prompt is pending raises SIGINT for the process. + */ + onCancel?: (reason: CancelReason) => Error; } + +/** How one pending question ended; a prompt with no answer can only end as `cancelled`, never fall through. */ +type PromptOutcome = { kind: 'answer'; value: unknown } | { kind: 'cancelled'; reason: CancelReason }; export class Inquirerer { private rl: readline.Interface | null; private keypress: TerminalKeypress | null; @@ -224,6 +238,13 @@ export class Inquirerer { private mutateArgs: boolean; private resolverRegistry: DefaultResolverRegistry; private timeout: number | undefined; + private resetsScreen: boolean; + /** Lines written since the current prompt last drew itself; what a redraw erases when the screen is kept. */ + private drawnLines = 0; + private cancelError: ((reason: CancelReason) => Error) | undefined; + private cancelPending: ((reason: CancelReason) => void) | null = null; + private inputEnded = false; + private onInputEnd: (() => void) | null = null; private _inactivityTimer: ReturnType | null = null; private _inactivityReject: ((err: PromptTimeoutError) => void) | null = null; @@ -242,7 +263,9 @@ export class Inquirerer { globalMaxLines = 10, mutateArgs = true, resolverRegistry = globalResolverRegistry, - timeout + timeout, + clearScreen = true, + onCancel } = options ?? {}; this.useDefaults = useDefaults; @@ -252,6 +275,8 @@ export class Inquirerer { this.input = input; this.globalMaxLines = globalMaxLines; this.resolverRegistry = resolverRegistry; + this.resetsScreen = clearScreen; + this.cancelError = onCancel; if (timeout !== undefined) { this.timeout = timeout; @@ -264,28 +289,62 @@ export class Inquirerer { } if (!noTty) { - this.rl = readline.createInterface({ - input, - output - }); + this.rl = this.createReadline(); this.keypress = new TerminalKeypress(noTty, input); + if (onCancel) { + this.keypress.onCancelKey((reason) => this.cancel(reason)); + this.onInputEnd = () => this.cancel('end-of-input'); + input.on('end', this.onInputEnd); + } } else { this.rl = null; this.keypress = null; } } + private createReadline(): readline.Interface { + const rl = readline.createInterface({ input: this.input, output: this.output }); + if (this.cancelError) { + // Without a listener readline closes itself on Ctrl-C; with onCancel the keypress handler decides instead. + rl.on('SIGINT', () => undefined); + // Readline also closes itself at the end of input (Ctrl-D on a terminal); a close by this class unsets this.rl first. + rl.on('close', () => { + if (this.rl === rl) this.cancel('end-of-input'); + }); + } + return rl; + } + private clearScreen() { - // same as console.clear() - this.output.write('\x1Bc'); // This is the escape sequence to clear the terminal screen. + if (this.resetsScreen) { + // same as console.clear() + this.output.write('\x1Bc'); // This is the escape sequence to clear the terminal screen. + return; + } + if (this.drawnLines > 0) this.output.write(`\x1b[${this.drawnLines}A\r\x1b[J`); + this.drawnLines = 0; } private write(message: string) { this.output.write(message); + this.drawnLines += message.split('\n').length - 1; } private log(message: string) { - this.output.write(message + '\n'); + this.write(message + '\n'); + } + + /** With onCancel set: the pending prompt ends as cancelled; Ctrl-C with no prompt pending sends SIGINT to the process. */ + private cancel(reason: CancelReason): void { + if (reason === 'end-of-input') this.inputEnded = true; + const settle = this.cancelPending; + if (settle) { + this.cancelPending = null; + this.write('\n'); + settle(reason); + } else if (reason === 'interrupt') { + process.kill(process.pid, 'SIGINT'); + } } private getInput(input: string) { @@ -537,16 +596,31 @@ export class Inquirerer { } while (ctx.needsInput) { + if (this.cancelError && !this.noTty && (this.inputEnded || this.input.readableEnded)) throw this.cancelError('end-of-input'); const timeoutPromise = this.startInactivityTimeout(question, ordered); + const cancelled = this.cancelError + ? new Promise((resolve) => { this.cancelPending = resolve; }) + : null; const removeActivityListener = this.setupInputActivityListener(); try { - const questionPromise = this.handleQuestionType(question, ctx); - obj[question.name] = timeoutPromise - ? await Promise.race([questionPromise, timeoutPromise]) - : await questionPromise; + this.drawnLines = 0; + const answered = this.handleQuestionType(question, ctx).then((value): PromptOutcome => ({ kind: 'answer', value })); + const outcome = await Promise.race([ + answered, + ...(timeoutPromise ? [timeoutPromise] : []), + ...(cancelled ? [cancelled.then((reason): PromptOutcome => ({ kind: 'cancelled', reason }))] : []) + ]); + switch (outcome.kind) { + case 'answer': + obj[question.name] = outcome.value; + break; + case 'cancelled': + throw this.cancelError(outcome.reason); + } } finally { removeActivityListener(); this.clearInactivityTimeout(); + this.cancelPending = null; } if (!this.isValid(question, obj, ctx)) { @@ -973,44 +1047,42 @@ export class Inquirerer { return null; // Password input requires interactive terminal } + // A readline interface writes back every key it reads, so none may be attached while a secret is typed. + // It is made again once the secret is read, for the prompts that use it. + const rl = this.rl; + this.rl = null; + rl.close(); + this.input.resume(); this.keypress.resume(); + const mask = question.mask ?? '*'; let input = ''; + const maskedLine = (): string => this.getInput(mask.repeat(Array.from(input).length)); + const redraw = (): void => this.write(`\r\x1b[2K${maskedLine()}`); - // Display the prompt with masked input - const display = (): void => { - this.clearScreen(); - const maskedInput = mask.repeat(input.length); - this.displayPrompt(question, ctx, maskedInput); - }; - - display(); - - // Handle backspace - this.keypress.on(KEY_CODES.BACKSPACE, () => { - if (input.length > 0) { - input = input.slice(0, -1); - display(); - } - }); + this.clearScreen(); + this.write(generatePromptMessage(question, ctx) + maskedLine()); - // Register alphanumeric, symbols, and space keypresses - const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !@#$%^&*()_+-=[]{}|;:\'",.<>?/`~\\'; - chars.split('').forEach(char => { - this.keypress.on(char, () => { - input += char; - display(); - }); + const erase = (): void => { + if (input.length === 0) return; + input = Array.from(input).slice(0, -1).join(''); + redraw(); + }; + this.keypress.on(KEY_CODES.BACKSPACE, erase); + this.keypress.on(KEY_CODES.BACKSPACE_LEGACY, erase); + this.keypress.onUnhandled((key) => { + // Escape sequences and control characters are keys, not text. + if (/[\u0000-\u001f\u007f-\u009f]/.test(key)) return; + input += key; + redraw(); }); return new Promise((resolve) => { this.keypress.on(KEY_CODES.ENTER, () => { this.keypress.pause(); - if (input.trim() !== '') { - resolve(input); - } else { - resolve(null); - } + this.write('\n'); + this.rl = this.createReadline(); + resolve(input.trim() !== '' ? input : null); }); }); } @@ -1528,8 +1600,13 @@ export class Inquirerer { // NOTE: use exit() to close! public close() { if (this.rl) { - this.rl.close(); + const rl = this.rl; this.rl = null; + rl.close(); + } + if (this.onInputEnd) { + this.input.removeListener('end', this.onInputEnd); + this.onInputEnd = null; } if (this.keypress) { this.keypress.destroy(); diff --git a/packages/inquirerer/test-utils/setup.ts b/packages/inquirerer/test-utils/setup.ts index 44fa62c..2fbab15 100644 --- a/packages/inquirerer/test-utils/setup.ts +++ b/packages/inquirerer/test-utils/setup.ts @@ -53,6 +53,12 @@ function setupReadlineMock(inputQueue: InputResponse[], currentInputIndex: numbe } export function setupTests(): () => TestEnvironment { + // The fake is set on the real readline module, which every test file in the same jest worker shares. + const createInterface = readline.createInterface; + afterAll(() => { + readline.createInterface = createInterface; + }); + let options: Partial; let mockWrite: jest.Mock; let mockInput: Readable;