@vigilbase/cli
Version:
Vigilbase CLI — security scanners, agent tools, and Vigilbase One from the terminal.
41 lines (40 loc) • 1.61 kB
JavaScript
import { constants } from 'node:fs';
import { open, rename, rm } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { dirname } from 'node:path';
import { assertFile, checkDirectory, checkExistingFile } from './store.js';
import { stripAcl } from './acl.js';
/** The same owner, mode, link and ACL checks as token storage. Never follow a key symlink. */
export async function readPrivateFile(path) {
if (!await checkDirectory(dirname(path)) || !await checkExistingFile(path))
return null;
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
try {
assertFile(await handle.stat(), path);
return await handle.readFile('utf8');
}
finally {
await handle.close();
}
}
/** Callers hold the credentials lock while creating or replacing a key. */
export async function writePrivateFile(path, value) {
await checkDirectory(dirname(path), true);
await checkExistingFile(path);
const temporary = `${path}.${randomUUID()}.tmp`;
const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
try {
await handle.chmod(0o600);
await stripAcl(temporary);
await handle.writeFile(value);
await handle.sync();
await handle.close();
await checkDirectory(dirname(path));
await checkExistingFile(path);
await rename(temporary, path);
}
finally {
await handle.close().catch(() => { });
await rm(temporary, { force: true });
}
}