private-config-file.ts 1001 B

123456789101112131415161718192021222324252627282930313233
  1. import fs from "node:fs";
  2. /** Config documents and their copies can contain plaintext credentials. */
  3. export const PRIVATE_CONFIG_FILE_MODE = 0o600;
  4. /** Remove non-owner access without changing an owner's read-only policy. */
  5. export function restrictConfigFileSync(filePath: string): void {
  6. if (process.platform === "win32") return;
  7. const mode = fs.statSync(filePath).mode;
  8. // Already-private files may live on read-only mounts or be immutable.
  9. if ((mode & 0o077) === 0) return;
  10. fs.chmodSync(filePath, mode & 0o700);
  11. }
  12. /** Restrict access before truncating or writing any secret-bearing content. */
  13. export function writePrivateConfigFileSync(
  14. filePath: string,
  15. content: string | Buffer,
  16. exclusive = false,
  17. ): void {
  18. const fd = fs.openSync(
  19. filePath,
  20. exclusive ? "wx" : "a",
  21. PRIVATE_CONFIG_FILE_MODE,
  22. );
  23. try {
  24. fs.fchmodSync(fd, PRIVATE_CONFIG_FILE_MODE);
  25. fs.ftruncateSync(fd, 0);
  26. fs.writeFileSync(fd, content);
  27. } finally {
  28. fs.closeSync(fd);
  29. }
  30. }