[keyman] portability, and stop keys from being silently invisible
Four things that each made keyman quietly less useful than it looked. **Clipboard.** `pbcopy` was spawned unconditionally, with a comment admitting it. Copy is now a list of commands per platform — pbcopy, clip, and wl-copy / xclip / xsel tried in order on everything else, because there is no single answer under Linux and trying them beats detecting the session type. Only an absent tool advances to the next candidate: one that ran and refused has an opinion. And if nothing is installed the key is printed, since "give me this public key" is answerable without a clipboard and used to be a dead end everywhere but macOS. Verified the round trip through real pbcopy/pbpaste. **Home directories.** `/home/<user>` was hardcoded — wrong on the platform this was written on. A named user is now looked for beside the current user's home first, which is right wherever homes live together whatever that directory is called, then in /home and /Users, and the failure names every path tried instead of feeding a nonexistent one to readdir. For the current user, `HOME` still wins, with `os.userInfo()` behind it: `process.env.HOME || ''` made an unset HOME fatal, which it is not in a cron job or a container. **Keys that are not named id_*.** A key called `deploy_ed25519` was absent from every menu with nothing said. It still is — the vault stores `<name minus id_>/id_<name>.age` and decrypt rebuilds the filename from the directory, so relaxing discovery means changing the on-disk layout, which the plan sizes as its largest single item and is not folded in here. What it does do is say so: any file whose first line carries a private key header and whose name lacks the prefix is now reported, per directory, with the reason. A bounded 64-byte read, because classifying a key is no reason to load one. **Plaintext hygiene.** A "Clear decrypted keys" entry, defaulting to no and listing what it would delete first, and a vault `.gitignore` written on first run covering the age identity and the tmp directory — which the README asked the user to do by hand. Never overwritten, and silent about a configured directory that sits outside the vault, since a .gitignore cannot speak for a path above itself and pretending otherwise reads as protection that is absent.
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import inquirer from 'inquirer';
|
||||
import { scanPrivateKeys } from './keyman.keys.js';
|
||||
|
||||
/**
|
||||
* Writes a `.gitignore` beside the vault, once.
|
||||
*
|
||||
* The README told the user to do this by hand. A vault holds the age identity and,
|
||||
* whenever anything has been decrypted, plaintext private keys — committing it is
|
||||
* the exact failure the tool exists to prevent, and it is one file to prevent it.
|
||||
*
|
||||
* Never overwritten: an existing file may say more than this one does.
|
||||
*/
|
||||
export function writeVaultGitignore(vaultRoot: string, tmpDir: string, keyPath: string) {
|
||||
const gitignore = path.join(vaultRoot, '.gitignore');
|
||||
if (fs.existsSync(gitignore)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Both are configurable and may be absolute, so either can sit outside the vault.
|
||||
// A .gitignore cannot speak about a path above itself, and claiming to would be
|
||||
// worse than saying nothing.
|
||||
const inside = (target: string) => {
|
||||
const relative = path.relative(vaultRoot, target);
|
||||
return relative && !relative.startsWith('..') && !path.isAbsolute(relative) ? relative : null;
|
||||
};
|
||||
|
||||
const tmp = inside(tmpDir);
|
||||
const key = inside(keyPath);
|
||||
|
||||
const lines = [
|
||||
'# Written by keyman. The encrypted keys under the keys directory are safe to',
|
||||
'# commit; nothing else here is.',
|
||||
...(key ? [key, `${key}.pub`] : []),
|
||||
...(tmp ? [`${tmp}/`] : []),
|
||||
'',
|
||||
];
|
||||
|
||||
fs.writeFileSync(gitignore, lines.join('\n'), { mode: 0o600 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the decrypted keys in the vault's tmp directory.
|
||||
*
|
||||
* The counterpart to `decrypt`, which had none: a plaintext private key stayed
|
||||
* there until someone remembered it, and "someone remembered" is not a security
|
||||
* control. Only the key pairs are removed — anything else in the directory is not
|
||||
* keyman's to delete.
|
||||
*/
|
||||
export async function clearDecryptedKeys(tmpDir: string) {
|
||||
const { keys } = scanPrivateKeys(tmpDir);
|
||||
|
||||
if (keys.length === 0) {
|
||||
console.log(`✅ Nothing decrypted in ${tmpDir}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`\n🔓 Decrypted keys in ${tmpDir}:`);
|
||||
for (const key of keys) {
|
||||
console.log(` ${key}`);
|
||||
}
|
||||
|
||||
const { confirmed } = await inquirer.prompt<{ confirmed: boolean }>([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'confirmed',
|
||||
message: `Delete ${keys.length === 1 ? 'this key' : `these ${keys.length} keys`}?`,
|
||||
// A key that exists only here — generated and not yet deployed — is gone for
|
||||
// good, so this is not a question to answer by pressing return.
|
||||
default: false,
|
||||
},
|
||||
]);
|
||||
|
||||
if (!confirmed) {
|
||||
console.log('⏭️ Nothing was deleted.');
|
||||
return;
|
||||
}
|
||||
|
||||
for (const key of keys) {
|
||||
for (const file of [key, `${key}.pub`]) {
|
||||
fs.rmSync(path.join(tmpDir, file), { force: true });
|
||||
}
|
||||
console.log(`🧹 Removed ${key}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { runTool, ToolNotFoundError } from './keyman.utils.js';
|
||||
|
||||
/** A clipboard command and the argv it wants, in the order they are tried. */
|
||||
interface ClipboardTool {
|
||||
binary: string;
|
||||
args: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The clipboard commands worth trying on a platform, best first.
|
||||
*
|
||||
* Linux is a list rather than a choice because there is no single answer:
|
||||
* `wl-copy` under Wayland, `xclip`/`xsel` under X11, and a user may have any
|
||||
* subset installed. Trying them in order and moving on from an absent one costs a
|
||||
* failed spawn and removes the need to detect the session type.
|
||||
*/
|
||||
export function clipboardTools(platform: string = process.platform): ClipboardTool[] {
|
||||
switch (platform) {
|
||||
case 'darwin':
|
||||
return [{ binary: 'pbcopy', args: [] }];
|
||||
case 'win32':
|
||||
return [{ binary: 'clip', args: [] }];
|
||||
default:
|
||||
return [
|
||||
{ binary: 'wl-copy', args: [] },
|
||||
{ binary: 'xclip', args: ['-selection', 'clipboard'] },
|
||||
{ binary: 'xsel', args: ['--clipboard', '--input'] },
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts `text` on the system clipboard.
|
||||
*
|
||||
* keyman used to spawn `pbcopy` unconditionally, with a comment saying so — which
|
||||
* made "copy public key" a dead end on every platform but macOS, and reported it
|
||||
* as a clipboard failure rather than as a missing tool.
|
||||
*
|
||||
* @returns the command that took it, or null if none was available
|
||||
*/
|
||||
export async function copyToClipboard(text: string, platform?: string): Promise<string | null> {
|
||||
for (const { binary, args } of clipboardTools(platform)) {
|
||||
try {
|
||||
await runTool(binary, args, { input: text });
|
||||
return binary;
|
||||
} catch (error) {
|
||||
// Only an absent tool is worth trying the next candidate for. One that ran
|
||||
// and refused has an opinion, and repeating the paste elsewhere is not it.
|
||||
if (!(error instanceof ToolNotFoundError)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,18 +1,19 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execa } from 'execa';
|
||||
import inquirer from 'inquirer';
|
||||
import { copyToClipboard } from './keyman.clipboard.js';
|
||||
import { reportSkippedKeys, scanPrivateKeys } from './keyman.keys.js';
|
||||
|
||||
export async function copyKey(sshDir: string, tmpDir: string) {
|
||||
const getKeys = (dir: string) => {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
return fs.readdirSync(dir).filter((key) => key.startsWith('id_') && !key.endsWith('.pub'));
|
||||
};
|
||||
const ssh = scanPrivateKeys(sshDir);
|
||||
const tmp = scanPrivateKeys(tmpDir);
|
||||
|
||||
const sshKeys = getKeys(sshDir);
|
||||
const tmpKeys = getKeys(tmpDir);
|
||||
const keys = [...new Set([...ssh.keys, ...tmp.keys])];
|
||||
|
||||
const keys = [...new Set([...sshKeys, ...tmpKeys])];
|
||||
// Before the empty check: "no SSH keys found" next to four unmanageable ones is
|
||||
// the case the report exists for.
|
||||
reportSkippedKeys(ssh.skipped, sshDir);
|
||||
reportSkippedKeys(tmp.skipped, tmpDir);
|
||||
|
||||
if (keys.length === 0) {
|
||||
console.log('⚠️ No SSH keys found.');
|
||||
@@ -40,19 +41,23 @@ export async function copyKey(sshDir: string, tmpDir: string) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pubKeyContent = fs.readFileSync(pubKeyPath, 'utf-8').trim();
|
||||
|
||||
try {
|
||||
const pubKeyContent = fs.readFileSync(pubKeyPath, 'utf-8').trim();
|
||||
const tool = await copyToClipboard(pubKeyContent);
|
||||
|
||||
// Detect OS and use appropriate clipboard command
|
||||
// Since the environment is Darwin, we prioritize pbcopy, but we can add others for completeness or use a simple check.
|
||||
// For this specific request on Darwin:
|
||||
const proc = execa('pbcopy');
|
||||
proc.stdin?.write(pubKeyContent);
|
||||
proc.stdin?.end();
|
||||
await proc;
|
||||
|
||||
console.log(`✅ Public key for ${selectedKey} copied to clipboard!`);
|
||||
if (tool) {
|
||||
console.log(`✅ Public key for ${selectedKey} copied to clipboard via ${tool}!`);
|
||||
return;
|
||||
}
|
||||
console.warn('⚠️ No clipboard command found.');
|
||||
} catch (error) {
|
||||
console.error(`❌ Failed to copy to clipboard: ${error}`);
|
||||
console.error(
|
||||
`❌ Failed to copy to clipboard: ${error instanceof Error ? error.message : error}`
|
||||
);
|
||||
}
|
||||
|
||||
// Printing it is the point of the operation; the clipboard was only the
|
||||
// convenient way to deliver it. A public key is not a secret.
|
||||
console.log(`\n${pubKeyContent}\n`);
|
||||
}
|
||||
|
||||
@@ -1,27 +1,19 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import inquirer from 'inquirer';
|
||||
import { reportSkippedKeys, scanPrivateKeys } from './keyman.keys.js';
|
||||
import { ToolNotFoundError } from './keyman.utils.js';
|
||||
import { storeInVault } from './keyman.vault.js';
|
||||
|
||||
/**
|
||||
* Private keys in a directory that may not exist.
|
||||
*
|
||||
* A first run has neither `~/.ssh` nor the tmp directory, and an unguarded
|
||||
* readdir there threw before the "nothing to encrypt" message could be reached.
|
||||
*/
|
||||
function privateKeysIn(dir: string): string[] {
|
||||
if (!fs.existsSync(dir)) {
|
||||
return [];
|
||||
}
|
||||
return fs.readdirSync(dir).filter((key) => key.startsWith('id_') && !key.endsWith('.pub'));
|
||||
}
|
||||
|
||||
export async function encryptKeys(sshDir: string, keysDir: string, tmpDir: string, pubkey: string) {
|
||||
const sshKeys = privateKeysIn(sshDir);
|
||||
const tmpKeys = privateKeysIn(tmpDir);
|
||||
const ssh = scanPrivateKeys(sshDir);
|
||||
const tmp = scanPrivateKeys(tmpDir);
|
||||
const sshKeys = ssh.keys;
|
||||
const tmpKeys = tmp.keys;
|
||||
const keys = [...new Set([...sshKeys, ...tmpKeys])];
|
||||
|
||||
reportSkippedKeys(ssh.skipped, sshDir);
|
||||
reportSkippedKeys(tmp.skipped, tmpDir);
|
||||
|
||||
if (keys.length === 0) {
|
||||
console.log('⚠️ No private SSH keys found to encrypt.');
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
/** The answer the USER prompt defaults to: whoever is running keyman. */
|
||||
export const CURRENT_USER = '@current';
|
||||
|
||||
/**
|
||||
* The home directory of the current user.
|
||||
*
|
||||
* `HOME` first, because a user who set it meant it, and `os.userInfo()` after,
|
||||
* which reads the passwd database and so still answers when `HOME` is unset — a
|
||||
* cron job, a `su` without `-l`, a container entrypoint. `process.env.HOME || ''`
|
||||
* treated all of those as a fatal error.
|
||||
*/
|
||||
function currentHome(): string | null {
|
||||
if (process.env.HOME) {
|
||||
return process.env.HOME;
|
||||
}
|
||||
try {
|
||||
return os.userInfo().homedir || null;
|
||||
} catch {
|
||||
// uv_os_get_passwd can fail outright when there is no passwd entry for the uid.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where another user's home directory is, without asking the system.
|
||||
*
|
||||
* The sibling of the current user's home comes first because it is right wherever
|
||||
* homes live together, whatever that directory is called — `/Users` on macOS,
|
||||
* `/home` on Linux, `/export/home` on the odd installation. keyman previously
|
||||
* hardcoded `/home/<user>`, which is wrong on the one platform it was written on.
|
||||
*
|
||||
* The candidates are checked for existence rather than guessed at, so a wrong one
|
||||
* produces an error naming what was tried instead of an empty `readdir`.
|
||||
*/
|
||||
function candidateHomes(user: string): string[] {
|
||||
const home = currentHome();
|
||||
const siblings = home ? [path.join(path.dirname(home), user)] : [];
|
||||
|
||||
return [...new Set([...siblings, path.join('/home', user), path.join('/Users', user)])];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the home directory for an answer to the USER prompt.
|
||||
*
|
||||
* @returns the directory, or null with the reason already reported
|
||||
*/
|
||||
export function resolveHomeDir(user: string): string | null {
|
||||
if (user === CURRENT_USER) {
|
||||
const home = currentHome();
|
||||
if (!home) {
|
||||
console.error('❌ Unable to determine HOME directory for the current user.');
|
||||
return null;
|
||||
}
|
||||
return home;
|
||||
}
|
||||
|
||||
const candidates = candidateHomes(user);
|
||||
const found = candidates.find((candidate) => fs.existsSync(candidate));
|
||||
|
||||
if (!found) {
|
||||
console.error(`❌ No home directory found for ${user}. Tried: ${candidates.join(', ')}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/** Present in the first line of every private key format ssh-keygen writes. */
|
||||
const PRIVATE_KEY_MARKER = 'PRIVATE KEY-----';
|
||||
|
||||
/** Enough for `-----BEGIN OPENSSH PRIVATE KEY-----`, and no more of a key than needed. */
|
||||
const HEADER_BYTES = 64;
|
||||
|
||||
/**
|
||||
* Whether a file opens with a private key header.
|
||||
*
|
||||
* A bounded read of the first line, not the file: classifying a key is no reason
|
||||
* to pull one into memory.
|
||||
*/
|
||||
function looksLikePrivateKey(file: string): boolean {
|
||||
let handle: number | undefined;
|
||||
try {
|
||||
handle = fs.openSync(file, 'r');
|
||||
const buffer = Buffer.alloc(HEADER_BYTES);
|
||||
const read = fs.readSync(handle, buffer, 0, HEADER_BYTES, 0);
|
||||
return buffer.subarray(0, read).toString('latin1').includes(PRIVATE_KEY_MARKER);
|
||||
} catch {
|
||||
// A directory, a socket, a file with no read permission — none of them a key.
|
||||
return false;
|
||||
} finally {
|
||||
if (handle !== undefined) {
|
||||
fs.closeSync(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface PrivateKeyScan {
|
||||
/** Keys keyman can manage: named `id_*`, which is what the vault layout assumes. */
|
||||
keys: string[];
|
||||
/** Private keys it found and cannot manage, because they are named otherwise. */
|
||||
skipped: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The private keys in a directory that may not exist.
|
||||
*
|
||||
* A first run has neither `~/.ssh` nor the tmp directory, and an unguarded readdir
|
||||
* there threw before the "nothing to encrypt" message could be reached.
|
||||
*
|
||||
* `skipped` exists because the `id_*` filter is silent: a key named
|
||||
* `deploy_ed25519` was simply absent from every menu, and pre-existing keys are
|
||||
* the population a key manager gets adopted to take over. Reporting them is not
|
||||
* managing them — see `reportSkippedKeys`.
|
||||
*/
|
||||
export function scanPrivateKeys(dir: string): PrivateKeyScan {
|
||||
if (!fs.existsSync(dir)) {
|
||||
return { keys: [], skipped: [] };
|
||||
}
|
||||
|
||||
const keys: string[] = [];
|
||||
const skipped: string[] = [];
|
||||
|
||||
// Sorted, because readdir order is the filesystem's business and a menu's order
|
||||
// should not depend on it.
|
||||
for (const file of fs.readdirSync(dir).sort()) {
|
||||
if (file.endsWith('.pub')) {
|
||||
continue;
|
||||
}
|
||||
if (file.startsWith('id_')) {
|
||||
// Not content-checked: what the menus offered has not changed.
|
||||
keys.push(file);
|
||||
} else if (looksLikePrivateKey(path.join(dir, file))) {
|
||||
skipped.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
return { keys, skipped };
|
||||
}
|
||||
|
||||
/**
|
||||
* Says which private keys were found and left alone, and why.
|
||||
*
|
||||
* The vault stores a key as `<name minus id_>/id_<name>.age` and `decrypt`
|
||||
* reconstructs the filename from the directory, so the prefix is baked into the
|
||||
* on-disk layout — which is why this is a report and not a fix.
|
||||
*/
|
||||
export function reportSkippedKeys(skipped: string[], dir: string): void {
|
||||
if (skipped.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const plural = skipped.length === 1 ? 'key' : 'keys';
|
||||
console.log(
|
||||
`ℹ️ Skipped ${skipped.length} private ${plural} in ${dir} not named id_*: ${skipped.join(', ')}`
|
||||
);
|
||||
console.log(' The vault layout requires the id_ prefix; rename to manage them here.');
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { reportSkippedKeys, scanPrivateKeys } from './keyman.keys.js';
|
||||
|
||||
interface KeyInfo {
|
||||
name: string;
|
||||
@@ -105,6 +106,12 @@ export async function listKeys(sshDir: string, vaultDir: string, tmpDir: string)
|
||||
}
|
||||
}
|
||||
|
||||
// A listing that omits keys without saying so is the worst place for the id_
|
||||
// assumption to be invisible: this is the screen a user checks it against.
|
||||
for (const dir of [sshDir, tmpDir]) {
|
||||
reportSkippedKeys(scanPrivateKeys(dir).skipped, dir);
|
||||
}
|
||||
|
||||
// Display results
|
||||
if (keyMap.size === 0) {
|
||||
console.log('⚠️ No SSH keys found.\n');
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import inquirer from 'inquirer';
|
||||
import { clearDecryptedKeys, writeVaultGitignore } from './keyman.clear.js';
|
||||
import { loadConfig, resolveConfigPaths } from './keyman.config.js';
|
||||
import { copyKey } from './keyman.copy.js';
|
||||
import { decryptKeys } from './keyman.decrypt.js';
|
||||
import { encryptKeys } from './keyman.encrypt.js';
|
||||
import { generateKey } from './keyman.generate.js';
|
||||
import { CURRENT_USER, resolveHomeDir } from './keyman.home.js';
|
||||
import { listKeys } from './keyman.list.js';
|
||||
import { extractAgePublicKey } from './keyman.utils.js';
|
||||
|
||||
@@ -25,14 +27,13 @@ export async function keyman() {
|
||||
{
|
||||
type: 'input',
|
||||
name: 'user',
|
||||
message: 'Specify USER (default: @current):',
|
||||
default: '@current',
|
||||
message: `Specify USER (default: ${CURRENT_USER}):`,
|
||||
default: CURRENT_USER,
|
||||
},
|
||||
]);
|
||||
|
||||
const homeDir = user === '@current' ? process.env.HOME || '' : `/home/${user}`;
|
||||
const homeDir = resolveHomeDir(user);
|
||||
if (!homeDir) {
|
||||
console.error('Error: Unable to determine HOME directory.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -43,6 +44,7 @@ export async function keyman() {
|
||||
for (const dir of [paths.vaultRoot, paths.keysDir, paths.tmpDir]) {
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
writeVaultGitignore(paths.vaultRoot, paths.tmpDir, paths.keyPath);
|
||||
|
||||
// Resolved on demand, because only generate and encrypt need a recipient, and
|
||||
// remembered once it succeeds. Retried while it has not: creating the identity
|
||||
@@ -73,6 +75,7 @@ export async function keyman() {
|
||||
{ name: '🆕 Generate key', value: 'generate' },
|
||||
{ name: '🔒 Encrypt keys', value: 'encrypt' },
|
||||
{ name: '🔓 Decrypt keys', value: 'decrypt' },
|
||||
{ name: '🧹 Clear decrypted keys', value: 'clear' },
|
||||
{ name: '❌ Quit', value: 'quit' },
|
||||
],
|
||||
},
|
||||
@@ -102,6 +105,9 @@ export async function keyman() {
|
||||
case 'decrypt':
|
||||
await decryptKeys(sshDir, paths.keysDir, paths.tmpDir, paths.keyPath);
|
||||
break;
|
||||
case 'clear':
|
||||
await clearDecryptedKeys(paths.tmpDir);
|
||||
break;
|
||||
case 'quit':
|
||||
console.log('\n👋 Goodbye!\n');
|
||||
running = false;
|
||||
|
||||
Reference in New Issue
Block a user