@heroku-cli/command
Version:
base class for Heroku CLI commands
292 lines (290 loc) • 13.2 kB
JavaScript
import { Scrubber } from '@heroku/js-blanket';
import childProcess from 'node:child_process';
const MISSING_CREDENTIAL_EXIT_CODE = 44;
const DIAGNOSTIC_REDACTION = '[SCRUBBED]';
const MIN_REDACTABLE_IDENTIFIER_LENGTH = 4;
const GET_AUTH_ERROR_PREFIX = 'Failed to retrieve credential';
/**
* Handles credential storage and retrieval using the Windows Credential Manager.
* Uses PowerShell commands to interact with the Windows.Security.Credentials.PasswordVault API.
*/
export class WindowsHandler {
scrubber = new Scrubber({
patterns: [
/Retrieve\("([^"]+)",\s*"([^"]+)"\)/g, // Scrub account in Retrieve("service", "account")
/PasswordCredential\("([^"]+)",\s*"([^"]+)",\s*"([^"]+)"\)/g, // Scrub account and token in PasswordCredential
],
});
/**
* Retrieves the authentication token from Windows Credential Manager.
* @param account - The account login to use (e.g. 'test@example.com')
* @param service - The service name to use
* @returns The stored authentication token.
* @throws Error if retrieval fails or the credential is not found.
*/
getAuth(account, service) {
const token = this.getAuthIfAvailable(account, service);
if (token === undefined) {
throw new Error('No credentials found');
}
return token;
}
/**
* Retrieves the authentication token from Windows Credential Manager when one exists.
* @param account - The account login to use (e.g. 'test@example.com')
* @param service - The service name to use
* @returns The stored authentication token, or undefined if it is not found.
* @throws Error if retrieval fails.
*/
getAuthIfAvailable(account, service) {
try {
const psCommand = `
$ErrorActionPreference = 'Stop'
[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$vault = New-Object Windows.Security.Credentials.PasswordVault
try {
$credential = $vault.Retrieve("${service}", "${account}")
} catch {
if ($_.Exception.HResult -eq -2147023728) {
exit ${MISSING_CREDENTIAL_EXIT_CODE}
}
throw
}
$credential.Password
`;
const output = childProcess.execSync(psCommand, { encoding: 'utf8', shell: 'powershell', stdio: ['pipe', 'pipe', 'pipe'] });
const token = output.trim();
if (!token) {
throw new Error('Token not found');
}
return token;
}
catch (error) {
const execError = error;
if (execError.status === MISSING_CREDENTIAL_EXIT_CODE) {
return undefined;
}
const message = [execError.message, execError.stderr?.toString()].filter(Boolean).join('\n');
const identifiers = [account, service].filter(Boolean);
const redacted = this.redactDiagnostic(message, identifiers);
const safeDiagnostic = redacted.ambiguous ? '' : this.getSafeDiagnostic(redacted.message);
throw new Error(redacted.ambiguous
? this.getSafeFallbackMessage(identifiers)
: this.getFailureMessage(safeDiagnostic, identifiers));
}
}
/**
* Lists all accounts stored in Windows Credential Manager for a given service.
* @param service - The service name to search for
* @returns Array of account names found for the service
* @throws Error if the search operation fails
*/
listAccounts(service) {
try {
const psCommand = `
$ErrorActionPreference = 'Stop'
[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$vault = New-Object Windows.Security.Credentials.PasswordVault
try {
$creds = $vault.FindAllByResource("${service}")
$creds | ForEach-Object { $_.UserName }
} catch {
# No credentials found for this resource
exit 0
}
`;
const output = childProcess.execSync(psCommand, { encoding: 'utf8', shell: 'powershell', stdio: ['pipe', 'pipe', 'ignore'] });
// Expected output format:
// user1@example.com
// user2@example.com
// ...
const accounts = output
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0);
return accounts;
}
catch (error) {
const { message } = error;
throw new Error(`Failed to list accounts in Windows Credential Manager: ${this.scrubError(message)}`);
}
}
/**
* Removes the authentication token from Windows Credential Manager.
* @param account - The account login to use (e.g. 'test@example.com')
* @param service - The service name to use
* @returns void
* @throws Error if the removal operation fails.
*/
removeAuth(account, service) {
try {
const psCommand = `
$ErrorActionPreference = 'Stop'
[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$vault = New-Object Windows.Security.Credentials.PasswordVault
$credential = $vault.Retrieve("${service}", "${account}")
$vault.Remove($credential)
`;
childProcess.execSync(psCommand, { encoding: 'utf8', shell: 'powershell', stdio: ['pipe', 'pipe', 'ignore'] });
}
catch (error) {
const { message } = error;
if (this.isMissingVaultCredential(message)) {
return;
}
throw new Error(`Failed to remove token from Windows Credential Manager: ${this.scrubError(message)}`);
}
}
/**
* Saves an authentication entry to Windows Credential Manager.
* If a credential with the same name already exists, it is removed before saving the new one.
* @param auth - The authentication entry containing account and token information to store.
* @returns void
* @throws Error if the save operation fails.
*/
saveAuth(auth) {
try {
try {
const removeCommand = `
$ErrorActionPreference = 'Stop'
[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$vault = New-Object Windows.Security.Credentials.PasswordVault
$credential = $vault.Retrieve("${auth.service}", "${auth.account}")
$vault.Remove($credential)
`;
childProcess.execSync(removeCommand, { encoding: 'utf8', shell: 'powershell', stdio: ['pipe', 'pipe', 'ignore'] });
}
catch {
// noop - item does not exist
}
const addCommand = `
$ErrorActionPreference = 'Stop'
[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$vault = New-Object Windows.Security.Credentials.PasswordVault
$credential = New-Object Windows.Security.Credentials.PasswordCredential("${auth.service}", "${auth.account}", "${auth.token}")
$vault.Add($credential)
`;
childProcess.execSync(addCommand, { encoding: 'utf8', shell: 'powershell', stdio: ['pipe', 'pipe', 'ignore'] });
}
catch (error) {
const { message } = error;
throw new Error(`Failed to store token in Windows Credential Manager: ${this.scrubError(message)}`);
}
}
containsIdentifier(message, identifiers) {
const normalizedMessage = message.toLowerCase();
return identifiers.some(identifier => {
if (identifier.length < MIN_REDACTABLE_IDENTIFIER_LENGTH) {
// Short identifiers are meaningful only as standalone tokens; substring checks
// would make ordinary words collide with values such as "o" or "t".
const escapedIdentifier = identifier.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw `\$&`);
return new RegExp(`(^|[^A-Za-z0-9_])${escapedIdentifier}($|[^A-Za-z0-9_])`, 'i').test(message);
}
return normalizedMessage.includes(identifier.toLowerCase());
});
}
getFailureMessage(detail, identifiers) {
const message = `${GET_AUTH_ERROR_PREFIX}${detail ? `: ${detail}` : ''}`;
return this.containsIdentifier(message, identifiers)
? this.getSafeFallbackMessage(identifiers)
: message;
}
/**
* Keeps only known-safe diagnostic text; arbitrary command output may contain other secrets.
*/
getSafeDiagnostic(message) {
const safeParts = [];
if (/\baccess denied\b/i.test(message))
safeParts.push('Access denied');
else if (/\bpermission denied\b/i.test(message))
safeParts.push('Permission denied');
else if (/^Token not found$/i.test(message.trim()))
safeParts.push('Token not found');
return safeParts.join(' ');
}
getSafeFallbackMessage(identifiers) {
const candidates = [
GET_AUTH_ERROR_PREFIX,
'Credential lookup failed',
'Authentication lookup failed',
'Lookup did not work',
'Action did not work',
'Request could not be completed',
'Credential retrieval failed',
'Unable to retrieve credential',
'Authentication request failed',
'Authentication problem',
'Token unavailable',
'No token available',
'The request failed',
'A problem occurred',
'The operation failed',
'Unable to continue',
'No result available',
'Something went wrong',
'Please try again',
'Oops',
'Try',
];
// Fixed prefixes and even short identifiers can collide with otherwise safe wording.
// Check every candidate against every nonempty identifier before returning it. Short
// identifiers use whole-token matching so incidental letters in useful wording are safe.
const candidate = candidates.find(message => message.trim().length > 0
&& !message.endsWith(':')
&& !/^[\p{P}\p{S}\s]+$/u.test(message)
&& !this.containsIdentifier(message, identifiers));
// Never include runtime values in the final fallback; this fixed text keeps the error useful
// even if unusual identifiers collide with every candidate above.
return (candidate ?? 'Credential retrieval could not be completed').replace(/:+$/, '');
}
/**
* PasswordVault.Retrieve throws when the credential is absent (e.g. netrc-only login).
*/
isMissingVaultCredential(message) {
const lower = message.toLowerCase();
return lower.includes('element not found')
|| lower.includes('specified credential could not be found')
|| lower.includes('0x80070490');
}
/**
* Removes runtime identifiers from command diagnostics without reprocessing replacement text.
* If an identifier is too short to redact without damaging ordinary diagnostics, omit the
* diagnostics rather than risk leaking it.
*/
redactDiagnostic(message, identifiers) {
const values = [...new Set(identifiers.filter(Boolean))];
if (values.some(value => value.length < MIN_REDACTABLE_IDENTIFIER_LENGTH)) {
return { ambiguous: true, message: '' };
}
if (values.length === 0)
return { ambiguous: false, message };
const escapedValues = values
.sort((a, b) => b.length - a.length)
.map(value => value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw `\$&`));
const identifierPattern = new RegExp(escapedValues.join('|'), 'gi');
let ambiguousMatch = false;
const redactedMessage = message.replaceAll(identifierPattern, (match, offset) => {
const precedingCharacter = message[offset - 1];
const followingCharacter = message[offset + match.length];
const hasAmbiguousLeftBoundary = /[A-Za-z0-9_]/.test(match[0] ?? '')
&& /[A-Za-z0-9_]/.test(precedingCharacter ?? '');
const hasAmbiguousRightBoundary = /[A-Za-z0-9_]/.test(match.at(-1) ?? '')
&& /[A-Za-z0-9_]/.test(followingCharacter ?? '');
if (hasAmbiguousLeftBoundary || hasAmbiguousRightBoundary) {
ambiguousMatch = true;
}
return DIAGNOSTIC_REDACTION;
});
return { ambiguous: ambiguousMatch, message: redactedMessage };
}
/**
* Scrubs account names and passwords/tokens from error messages.
*
* @param message - The error message to scrub
* @returns The scrubbed error message with sensitive data replaced by "[SCRUBBED]"
*/
scrubError(message) {
const result = this.scrubber.scrub({ message });
return result.data.message;
}
}