37 lines
1.4 KiB
TypeScript
37 lines
1.4 KiB
TypeScript
import { mkdirSync, mkdtempSync } from "node:fs";
|
|
|
|
/**
|
|
* Creation modes that must not depend on the caller's ambient umask.
|
|
*
|
|
* `mkdir(path, { mode: 0o700 })` and `open(path, ..., 0o600)` are requests, not
|
|
* guarantees: the kernel subtracts the process umask from every one of them. A
|
|
* runner hardened with `umask 0777` therefore produces directories nobody can
|
|
* enter and files nobody can read, and the failure surfaces far from its cause
|
|
* — as `tar` failing to mkdir a nested path, or as EACCES opening a staging
|
|
* leaf this process created moments earlier.
|
|
*
|
|
* Release evidence has to be exactly private, so the mode is pinned rather than
|
|
* inherited. The pin is held across a synchronous call only: nothing else in
|
|
* this process can interleave, so the global umask is never observably changed.
|
|
*/
|
|
const PRIVATE_UMASK = 0o077;
|
|
|
|
export function withPrivateUmask<T>(operation: () => T): T {
|
|
const previous = process.umask(PRIVATE_UMASK);
|
|
try {
|
|
return operation();
|
|
} finally {
|
|
process.umask(previous);
|
|
}
|
|
}
|
|
|
|
/** Creates a uniquely named private directory under `prefix`. */
|
|
export function makePrivateTemporaryDirectory(prefix: string): string {
|
|
return withPrivateUmask(() => mkdtempSync(prefix));
|
|
}
|
|
|
|
/** Creates `target` privately, failing if it already exists. */
|
|
export function makePrivateDirectory(target: string): void {
|
|
withPrivateUmask(() => mkdirSync(target, { mode: 0o700 }));
|
|
}
|