install.fairie/home/dot_local/bin/executable_get-secret
2024-05-28 06:55:42 +00:00

70 lines
2.1 KiB
Text

#!/usr/bin/env zx
// @file Get Secret
// @brief This helper utility allows you to return decrypted secrets or check the file system / environment variables to ensure the secrets are available
const customArgv = minimist(process.argv.slice(3), {
boolean: [
'exists'
],
alias: {
e: 'exists',
}
})
const secretDir = `${os.homedir()}/.local/share/chezmoi/home/.chezmoitemplates/secrets`
if (customArgv.exists && !customArgv._.length) {
console.error('Must pass one or more secrets to check for when using --exists', customArgv)
process.exit(1)
} else if (!customArgv.exists && (!customArgv._.length || customArgv._.length > 1)) {
console.log('Must pass exactly one argument.', customArgv)
process.exit(1)
} else {
if (customArgv.exists) {
ensureAllChezmoiSecrets(customArgv._)
} else {
const secretName = customArgv._[0]
if (process.env[secretName]) {
console.log(process.env[secretName])
process.exit(0)
}
// Check for presence of secret in appropriate Chezmoi directory
const secretPath = `${secretDir}/${secretName}`
const fileExists = fs.existsSync(`${secretPath}`)
if (fileExists) {
getChezmoiSecret(secretPath)
} else {
console.error(`The file ${secretPath} does not exist!`)
process.exit(1)
}
}
}
async function getChezmoiSecret(secretPath) {
try {
const decryptedSecret = await $`cat "${secretPath}" | chezmoi decrypt`
console.log(decryptedSecret.stdout)
process.exit(0)
} catch (e) {
console.error(`Error decrypting ${secretPath}`, e)
process.exit(1)
}
}
async function ensureAllChezmoiSecrets(secretNames) {
try {
const promises = []
for (let secretName of secretNames) {
if (!process.env[secretName]) {
promises.push(fs.promises.stat(`${secretDir}/${secretName}`))
}
}
await Promise.all(promises)
process.exit(0)
} catch (e) {
console.error(`One or more of the secret names are not available as environment variables or in ${secretDir}`)
console.log(`Secrets that were checked:`, customArgv._)
process.exit(1)
}
}