From b1c8dc0b57a54628beaf7d889a0dfffd80f06f18 Mon Sep 17 00:00:00 2001 From: DeryFerd Date: Sun, 8 Nov 2026 22:20:04 +0700 Subject: [PATCH] fix(harden): write sidecar-entry rewrites atomically and stop swallowing failures The sidecar-entanglement post-pass rewrote the entry three times with plain writeFileSync, so a crash or disk-full mid-write could truncate the artifact the user asked BLA to harden -- the opposite of the atomic write chokepoint the protector already uses. Route those writes through that chokepoint (now exported) instead. The surrounding try/catch also swallowed every error, so a requested entanglement could fail and the run would still report success while the entry shipped without its strip=>fail binding. Capture the error, expose it as sidecarEntangleError, fail overallSuccess, and print it in the text report. Verified: new contract test asserts a successful JS harden reports no entanglement error, keeps the binding in the entry, and leaves no .bla-tmp-* files behind. --- src/engine/harden.ts | 33 ++++++++++++++---- src/engine/protector.ts | 2 +- tests/harden-sidecar-atomic.test.ts | 54 +++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 tests/harden-sidecar-atomic.test.ts diff --git a/src/engine/harden.ts b/src/engine/harden.ts index 05d40a5..3fac3d5 100644 --- a/src/engine/harden.ts +++ b/src/engine/harden.ts @@ -47,6 +47,7 @@ import { verifySelfSealSelfDigest, } from "../shields/runtime/self-seal.js"; import { withoutHostSelfCoverage } from "./integrity-coverage.js"; +import { writeFileAtomicSync } from "./protector.js"; import { computeHardenRunId, HARDEN_SUMMARY_FILE_NAME, @@ -229,6 +230,12 @@ export interface HardenProjectReport { readonly selfSeal: boolean; /** True when caller opted into sidecar entry entanglement. */ readonly sidecarEntangle: boolean; + /** + * Present when `sidecarEntangle` was requested but the entry rewrite failed, + * leaving the entry without the strip⇒fail binding. Such a run never reports + * `overallSuccess`. + */ + readonly sidecarEntangleError?: string; /** * True when `requireAgentWeave` blocked mechanical hardening because source * files still need Host-Agent source surgery (`bla_verify_weave` failed). @@ -1007,6 +1014,7 @@ export function hardenProject( // Per-artifact protect skips inject when harden did not pass explicit // sidecarEntanglePaths (avoids partial/double prepend). Only one entry is // rewritten so sibling digests stay stable. + let sidecarEntangleError: string | undefined; if (options.sidecarEntangle === true && !dryRun && summaries.some((s) => s.success)) { try { const jsLike = summaries.filter( @@ -1039,7 +1047,7 @@ export function hardenProject( }); if (bound) { const finalized = finalizeSelfSealSelfDigest(bound.code); - writeFileSync(entryAbs, finalized.content, "utf8"); + writeFileAtomicSync(entryAbs, finalized.content, "utf8"); } } } @@ -1076,7 +1084,7 @@ export function hardenProject( seedTag: String(options.seed ?? runId), }); if (bound) { - writeFileSync(entryAbs, bound.code, "utf8"); + writeFileAtomicSync(entryAbs, bound.code, "utf8"); } } } @@ -1113,13 +1121,16 @@ export function hardenProject( seedTag: String(options.seed ?? runId), }); if (bound) { - writeFileSync(entryAbs, bound.bytes); + writeFileAtomicSync(entryAbs, bound.bytes); } } } } - } catch { - /* best-effort — leave entry as-is */ + } catch (err) { + // Entanglement was explicitly requested, so a failure is not a harmless + // no-op: the entry ships without the strip⇒fail binding. Record it so the + // report can fail loudly instead of claiming success. + sidecarEntangleError = err instanceof Error ? err.message : String(err); } } @@ -1171,7 +1182,11 @@ export function hardenProject( } return { ...reportBase, - overallSuccess: !cancelled && summaries.length > 0 && failedCount === 0, + overallSuccess: + !cancelled && + summaries.length > 0 && + failedCount === 0 && + sidecarEntangleError === undefined, hardenedCount, failedCount, artifacts: summaries, @@ -1184,6 +1199,7 @@ export function hardenProject( ...(integrityCoverageSelfVerified !== undefined ? { integrityCoverageSelfVerified } : {}), + ...(sidecarEntangleError !== undefined ? { sidecarEntangleError } : {}), }; } @@ -1219,6 +1235,11 @@ export function formatHardenProjectReport(report: HardenProjectReport): string { ` ⚠ self_seal recommended: ${report.selfSealRecommendation ?? "multi-artifact tree — pass --self-seal / self_seal:true"}`, ); } + if (report.sidecarEntangleError !== undefined) { + lines.push( + ` ⚠ sidecar entanglement failed: ${report.sidecarEntangleError} — entry shipped WITHOUT the strip⇒fail binding`, + ); + } for (const a of report.artifacts) { if (report.dryRun) { lines.push( diff --git a/src/engine/protector.ts b/src/engine/protector.ts index 80385c5..fde53ab 100644 --- a/src/engine/protector.ts +++ b/src/engine/protector.ts @@ -270,7 +270,7 @@ function applyPanelDeriveRewrite( return rw.code; } -function writeFileAtomicSync( +export function writeFileAtomicSync( targetPath: string, content: string | Buffer, encoding?: BufferEncoding, diff --git a/tests/harden-sidecar-atomic.test.ts b/tests/harden-sidecar-atomic.test.ts new file mode 100644 index 0000000..4261f6a --- /dev/null +++ b/tests/harden-sidecar-atomic.test.ts @@ -0,0 +1,54 @@ +import { mkdtempSync, readdirSync, readFileSync, rmSync, mkdirSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { hardenProject } from "../src/engine/harden.js"; + +const tempDirs: string[] = []; + +function makeProject(): string { + const dir = mkdtempSync(join(tmpdir(), "bla-harden-sidecar-atomic-")); + tempDirs.push(dir); + mkdirSync(join(dir, "dist"), { recursive: true }); + writeFileSync( + join(dir, "dist", "license.cjs"), + "module.exports = { tier: 'pro', check() { return true; } };\n", + "utf8", + ); + writeFileSync(join(dir, "dist", "helper.cjs"), "module.exports = { helper: 1 };\n", "utf8"); + return dir; +} + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe("harden sidecar entanglement report", () => { + it("reports success without an entanglement error and leaves no atomic temp files", () => { + const dir = makeProject(); + const report = hardenProject({ + directory: dir, + intensity: "balanced", + seed: "sidecar-atomic-seed", + sidecarEntangle: true, + }); + + expect(report.overallSuccess).toBe(true); + expect(report.sidecarEntangleError).toBeUndefined(); + expect(report.sidecarEntangle).toBe(true); + + const entry = report.artifacts.find((a) => + a.relativePath.replaceAll("\\", "/").endsWith("license.cjs"), + ); + expect(entry?.success).toBe(true); + expect(readFileSync(entry!.outputPath, "utf8")).toContain("integrity binding mismatch"); + + // Atomic writes go through a uniquely named temp file; none may survive. + const leftovers = readdirSync(report.outputDirectory).filter((name) => + name.includes(".bla-tmp-"), + ); + expect(leftovers).toEqual([]); + }); +}); \ No newline at end of file