fix(encrypt-strings): write through the shared atomic link-guarded writer (#163)

This commit is contained in:
Dery Ferdika
2026-11-12 14:00:35 +07:00
committed by GitHub
parent 3a3922be26
commit c9356ba847
2 changed files with 30 additions and 3 deletions
+7 -2
View File
@@ -19,10 +19,10 @@ import {
readdirSync,
readFileSync,
statSync,
writeFileSync,
} from "node:fs";
import { basename, dirname, join, relative, resolve } from "node:path";
import { SeededPrng } from "../core/prng.js";
import { writeFileAtomicSync } from "./protector.js";
import {
classifySensitiveLiteral,
extractStringLiterals,
@@ -535,7 +535,12 @@ export function encryptStrings(options: EncryptStringsOptions): EncryptStringsRe
let written = false;
if (result.encrypted.length > 0 && !options.dryRun) {
if (outDir) mkdirSync(dirname(outPath), { recursive: true });
writeFileSync(outPath, result.code, "utf8");
// Same atomic, link-guarded writer the rest of the engine uses: an
// outDir copy must not follow a planted symlink/hardlink, while the
// in-place rewrite of the caller's own file keeps that opt-in.
writeFileAtomicSync(outPath, result.code, "utf8", {
allowLinkWriteThrough: outDir === null,
});
written = true;
}
+23 -1
View File
@@ -1,4 +1,4 @@
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { linkSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -60,6 +60,28 @@ module.exports = { unlock };
);
});
it("refuses to write through a hardlinked output path inside outDir", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-enc-link-"));
const outDir = join(dir, "out");
mkdirSync(outDir, { recursive: true });
writeFileSync(
join(dir, "license.cjs"),
`module.exports.flag = "FLAG{hardlink_target_must_survive}";\n`,
);
const victim = join(dir, "victim.txt");
writeFileSync(victim, "PRECIOUS-ORIGINAL");
try {
linkSync(victim, join(outDir, "license.cjs"));
} catch {
return; // hardlinks unsupported on this filesystem
}
const report = encryptStrings({ path: dir, seed: "link-test", outDir });
expect(report.status).toBe("error");
expect(report.error ?? "").toMatch(/symlink or hardlinked/);
expect(readFileSync(victim, "utf8")).toBe("PRECIOUS-ORIGINAL");
});
it("same seed is reproducible; different seed differs", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-enc-repro-"));
writeFileSync(