70 lines
2.1 KiB
TypeScript
70 lines
2.1 KiB
TypeScript
export const SUDO_PTY_PROMPT = '[gcoord-sudo-prompt] ';
|
|
|
|
export function posixSingleQuote(value: string): string {
|
|
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
}
|
|
|
|
export function buildEnvPrefix(env?: Record<string, string>): string {
|
|
if (!env) return '';
|
|
const parts: string[] = [];
|
|
for (const [key, val] of Object.entries(env)) {
|
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
|
|
throw new Error(`Invalid environment variable name: ${key}`);
|
|
}
|
|
parts.push(`export ${key}=${posixSingleQuote(val)}`);
|
|
}
|
|
return parts.length > 0 ? `${parts.join('; ')}; ` : '';
|
|
}
|
|
|
|
export function prepareSudoExecution(
|
|
command: string,
|
|
options: {
|
|
sudoPassword?: string;
|
|
stdin?: Buffer | string;
|
|
ptyPrompt?: boolean;
|
|
} = {},
|
|
): { command: string; stdin?: Buffer; ptyPassword?: string } {
|
|
const quoted = posixSingleQuote(command);
|
|
if (options.sudoPassword !== undefined && options.sudoPassword.length > 0) {
|
|
if (options.ptyPrompt) {
|
|
const extraStdin =
|
|
options.stdin === undefined
|
|
? undefined
|
|
: typeof options.stdin === 'string'
|
|
? Buffer.from(options.stdin, 'utf8')
|
|
: Buffer.from(options.stdin);
|
|
return {
|
|
command: `sudo -S -k -p ${posixSingleQuote(SUDO_PTY_PROMPT)} sh -c ${quoted}`,
|
|
stdin: extraStdin,
|
|
ptyPassword: options.sudoPassword,
|
|
};
|
|
}
|
|
|
|
const pwPrefix = Buffer.from(`${options.sudoPassword}\n`, 'utf8');
|
|
let combined = pwPrefix;
|
|
if (options.stdin !== undefined && options.stdin.length > 0) {
|
|
const extra =
|
|
typeof options.stdin === 'string'
|
|
? Buffer.from(options.stdin, 'utf8')
|
|
: options.stdin;
|
|
combined = Buffer.concat([pwPrefix, extra]);
|
|
pwPrefix.fill(0);
|
|
}
|
|
return {
|
|
command: `sudo -S -k -p '' sh -c ${quoted}`,
|
|
stdin: combined,
|
|
};
|
|
}
|
|
|
|
const extraStdin =
|
|
options.stdin === undefined
|
|
? undefined
|
|
: typeof options.stdin === 'string'
|
|
? Buffer.from(options.stdin, 'utf8')
|
|
: Buffer.from(options.stdin);
|
|
|
|
return {
|
|
command: `sudo -n sh -c ${quoted}`,
|
|
stdin: extraStdin,
|
|
};
|
|
}
|