Skip to content

armgit / bla

Public Imported from GitHub
0

🛡️ BLA (Blind LLM Agents) — Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, and WebAssembly against AI reverse-engineering agents like REA. Poison -> Exhaust -> Hallucinate.

fix: preserve Safetensors integrity and reject malformed model inputs

Codex9c6a013e0d62
diff --git a/README.md b/README.md
index 87a2c3e..072d9ad 100644
--- a/README.md
+++ b/README.md
@@ -288,3 +288,26 @@ Issues and pull requests are welcome at [qybaihe/bla](https://github.com/qybaihe
## License
[MIT](LICENSE)
+
+### Safetensors integrity boundary
+
+Safetensors rewriting validates the input before creating output paths and preserves
+all tensor descriptors, tensor data bytes, and existing string metadata (including
+colliding BLA metadata keys). The invalid top-level `_bla_nesting_breaker` payload is
+disabled at **every intensity**; `triggeredJsonNestingBreaker` remains in the API for
+compatibility and is always `false`. Previously generated malformed models are
+rejected, not repaired or replaced with synthetic weights.
+
+The local validator checks UTF-8/JSON, duplicate fields, string metadata, nonnegative
+safe-integer shapes/offsets, byte sizes, contiguous nonoverlapping tensor ranges,
+and complete data coverage. It follows the structural requirements in the
+[official Safetensors implementation](https://github.com/huggingface/safetensors/blob/main/safetensors/src/tensor.rs)
+and emits an 8-byte-aligned header. Its deliberately conservative supported dtype
+subset is `BOOL`, `U8`, `I8`, `U16`, `I16`, `F16`, `BF16`, `U32`, `I32`, `F32`, `U64`,
+`I64`, and `F64`. Other dtypes are reported as unsupported; this is not a claim that
+those models are invalid. Headers above 100 MB and integers beyond JavaScript's
+safe range are refused rather than silently rounded.
+
+These are structural and byte-preservation checks, **not** official-loader
+validation, model inference, or evidence of effectiveness against REA. The
+Safetensors benchmark's functional test remains `not-run`.
diff --git a/src/engine/protector.ts b/src/engine/protector.ts
index 75fa841..96919ce 100644
--- a/src/engine/protector.ts
+++ b/src/engine/protector.ts
@@ -58,6 +58,11 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {
const prng = new SeededPrng(seed);
const chaffPayloads = generateChaffPayloads(prng, intensity);
+ // Complete model validation/serialization before creating any output path.
+ const safetensorsResult = format === "model-safetensors"
+ ? protectSafetensorsBuffer(readFileSync(absInput), { intensity, seed })
+ : undefined;
+
const beforeAudit = auditTarget(absInput);
const absOutput = resolve(
options.outputPath ?? deriveDefaultOutputPath(absInput, options.inPlace),
@@ -281,10 +286,8 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {
binarySectionsPatched = res.honeyTablesInjected + res.generatedTrapColumnsAdded;
counteredVectors.add("sqlite-database-inspection");
} else if (format === "model-safetensors") {
- const rawModel = readFileSync(absInput);
- const res = protectSafetensorsBuffer(rawModel, { intensity, seed });
+ const res = safetensorsResult!;
writeFileSync(absOutput, res.buffer);
- decoyFunctionsInjected = 16;
chaffPayloadsEmbedded = res.chaffPayloadsEmbedded;
binarySectionsPatched = res.triggeredJsonNestingBreaker ? 2 : 1;
counteredVectors.add("model-artifact-inspection");
diff --git a/src/index.ts b/src/index.ts
index b687e6e..ede6b1d 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -51,6 +51,8 @@ export {
} from "./shields/formats/sqlite.js";
export {
buildSafetensorsBuffer,
+ validateSafetensorsBuffer,
+ InvalidSafetensorsError,
inspectModelBuffer,
protectSafetensorsBuffer,
protectGgufBuffer,
diff --git a/src/shields/formats/model.ts b/src/shields/formats/model.ts
index f07cf73..98c49f1 100644
--- a/src/shields/formats/model.ts
+++ b/src/shields/formats/model.ts
@@ -1,4 +1,3 @@
-import { REA_INTERNAL_LIMITS } from "../../identity.js";
import { SeededPrng } from "../../core/prng.js";
import type { ProtectionIntensity } from "../../core/types.js";
import { generateChaffPayloads } from "../chaff/chaff-generator.js";
@@ -12,14 +11,113 @@ export interface ModelInspectionSummary {
readonly blaProtected: boolean;
}
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/** Invalid or unsupported input is never replaced with synthetic weights. */
+export class InvalidSafetensorsError extends Error {
+ constructor(reason: string) {
+ super(`Invalid or unsupported Safetensors input: ${reason}`);
+ this.name = "InvalidSafetensorsError";
+ }
+}
+
+// Conservative supported dtype subset. Unknown/new dtypes fail closed.
+const DTYPE_BYTES: Readonly<Record<string, number>> = Object.freeze({
+ BOOL: 1, U8: 1, I8: 1, I16: 2, U16: 2, F16: 2, BF16: 2,
+ I32: 4, U32: 4, F32: 4, I64: 8, U64: 8, F64: 8,
+});
+
+/** Structural validation only: this does not run model inference. */
+export function validateSafetensorsBuffer(bytes: Buffer): {
+ header: Record<string, unknown>; tensorData: Buffer;
+} {
+ const fail = (reason: string): never => { throw new InvalidSafetensorsError(reason); };
+ if (bytes.length < 10) fail("truncated header");
+ const length = bytes.readBigUInt64LE(0);
+ if (length > 100_000_000n || length > BigInt(bytes.length - 8) || length < 2n) {
+ fail("invalid header length");
+ }
+ const end = 8 + Number(length);
+ let text: string;
+ let header: unknown;
+ try {
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(8, end));
+ if (!text.startsWith("{")) fail("header must start with an object");
+ header = JSON.parse(text);
+ // JSON.parse otherwise silently loses duplicate fields, including tensor names.
+ const stack: Array<Set<string> | null> = [];
+ const tokens = /"(?:[^"\\]|\\.)*"|[{}\[\]]/g;
+ for (const token of text.matchAll(tokens)) {
+ const value = token[0];
+ if (value === "{") stack.push(new Set());
+ else if (value === "[") stack.push(null);
+ else if (value === "}" || value === "]") stack.pop();
+ else {
+ const decoded = JSON.parse(value) as string;
+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(decoded)) {
+ fail("invalid Unicode string");
+ }
+ if (text.slice(token.index! + value.length).trimStart().startsWith(":")) {
+ const keys = stack.at(-1);
+ if (keys?.has(decoded)) fail("duplicate JSON field");
+ keys?.add(decoded);
+ }
+ }
+ }
+ } catch (error) {
+ if (error instanceof InvalidSafetensorsError) throw error;
+ return fail("invalid UTF-8 or JSON header");
+ }
+ if (!isRecord(header)) return fail("header must be an object");
+ if (Object.hasOwn(header, "__metadata__") &&
+ (!isRecord(header.__metadata__) || Object.values(header.__metadata__).some(v => typeof v !== "string"))) {
+ fail("metadata must be a string-to-string object");
+ }
+ const ranges: Array<[number, number]> = [];
+ for (const [name, descriptor] of Object.entries(header)) {
+ if (name === "__metadata__") continue;
+ if (!isRecord(descriptor)) return fail("invalid tensor descriptor");
+ const { dtype, shape, data_offsets: offsets } = descriptor;
+ if (typeof dtype !== "string" || !Object.hasOwn(DTYPE_BYTES, dtype)) fail("unsupported tensor dtype");
+ if (!Array.isArray(shape) || !shape.every(n => Number.isSafeInteger(n) && n >= 0)) {
+ return fail("invalid tensor shape");
+ }
+ if (!Array.isArray(offsets) || offsets.length !== 2 || !offsets.every(n => Number.isSafeInteger(n) && n >= 0)) {
+ return fail("invalid tensor offsets");
+ }
+ const [start, stop] = offsets as [number, number];
+ let size = shape.includes(0) ? 0n : BigInt(DTYPE_BYTES[dtype as string]!);
+ if (size !== 0n) {
+ for (const dimension of shape) {
+ size *= BigInt(dimension);
+ if (size > BigInt(Number.MAX_SAFE_INTEGER)) fail("unsupported tensor size beyond safe range");
+ }
+ }
+ if (stop < start || stop > bytes.length - end || size !== BigInt(stop - start)) fail("tensor byte size mismatch");
+ ranges.push([start, stop]);
+ }
+ ranges.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
+ let cursor = 0;
+ for (const [start, stop] of ranges) {
+ if (start !== cursor) fail("overlapping or incomplete tensor data");
+ cursor = stop;
+ }
+ if (cursor !== bytes.length - end) fail("unreferenced tensor data");
+ return { header, tensorData: bytes.subarray(end) };
+}
+
/**
- * Builds avalid Safetensors model buffer (`.safetensors`) from a header object and raw data bytes.
+ * Serializes a Safetensors header and data buffer (does not validate caller input) (`.safetensors`) from a header object and raw data bytes.
*/
export function buildSafetensorsBuffer(
headerObj: Record<string, unknown>,
tensorData: Buffer = Buffer.alloc(16, 0),
): Buffer {
- const jsonBytes = Buffer.from(JSON.stringify(headerObj), "utf8");
+ const rawJson = Buffer.from(JSON.stringify(headerObj), "utf8");
+ const jsonBytes = Buffer.alloc(Math.ceil(rawJson.length / 8) * 8, 0x20);
+ rawJson.copy(jsonBytes);
const lenPrefix = Buffer.alloc(8);
lenPrefix.writeBigUInt64LE(BigInt(jsonBytes.length), 0);
return Buffer.concat([lenPrefix, jsonBytes, tensorData]);
@@ -56,29 +154,16 @@ export function inspectModelBuffer(bytes: Buffer): ModelInspectionSummary {
// Check Safetensors (8-byte LE uint64 header size + JSON starting with '{')
if (bytes.length >= 10 && bytes[8] === 0x7b) {
try {
- const headerSize = Number(bytes.readBigUInt64LE(0));
- if (headerSize > 0 && 8 + headerSize <= bytes.length) {
- const jsonText = bytes.subarray(8, 8 + headerSize).toString("utf8");
- const parsed = JSON.parse(jsonText) as Record<string, unknown>;
- const keys = Object.keys(parsed);
- const tensorCount = keys.filter((k) => k !== "__metadata__").length;
- const meta =
- typeof parsed.__metadata__ === "object" && parsed.__metadata__ !== null
- ? Object.keys(parsed.__metadata__ as Record<string, unknown>)
- : [];
- const exceedsReaNestingLimit = jsonText.includes('"_bla_nesting_breaker"');
- const blaProtected =
- exceedsReaNestingLimit ||
- meta.some((k) => k.startsWith("bla.") || k.startsWith("enclave."));
- return {
- validModel: true,
- format: "safetensors",
- tensorCount,
- metadataCount: meta.length,
- exceedsReaNestingLimit,
- blaProtected,
- };
- }
+ const { header: parsed } = validateSafetensorsBuffer(bytes);
+ const meta = Object.keys((parsed.__metadata__ ?? {}) as Record<string, string>);
+ return {
+ validModel: true,
+ format: "safetensors",
+ tensorCount: Object.keys(parsed).filter(k => k !== "__metadata__").length,
+ metadataCount: meta.length,
+ exceedsReaNestingLimit: false,
+ blaProtected: meta.some(k => k.startsWith("bla.") || k.startsWith("enclave.")),
+ };
} catch {
// Fallthrough
}
@@ -95,14 +180,8 @@ export function inspectModelBuffer(bytes: Buffer): ModelInspectionSummary {
}
/**
- * Protects a `.safetensors` AI model artifact against REA's `inspect-model-artifact`
- * (`src/model/SafetensorsHeader.ts` & `src/model/ModelFormat.ts`):
- *
- * 1. Embeds enclave weight-partition and TEE delegation manifests into `__metadata__`.
- * 2. When `intensity === "bankrupt"` or `"maximum"`, embeds a 35-level nested JSON structure
- * under `_bla_nesting_breaker` (`> MODEL_JSON_NESTING = 32` in `SafetensorsHeader.ts:74`),
- * causing REA's `HeaderJson` parser to immediately throw:
- * `ModelFormatFailure("capacity", "Safetensors JSON nesting exceeds 32 levels", "json-nesting")`!
+ * Adds metadata without changing tensors. Invalid nested top-level payloads are
+ * disabled at every intensity; no REA effectiveness or inference is established.
*/
export function protectSafetensorsBuffer(
bytes: Buffer,
@@ -115,58 +194,36 @@ export function protectSafetensorsBuffer(
readonly chaffPayloadsEmbedded: number;
readonly triggeredJsonNestingBreaker: boolean;
} {
+ const { header: headerObj, tensorData } = validateSafetensorsBuffer(bytes);
const intensity = options.intensity ?? "balanced";
const prng = new SeededPrng(options.seed ?? "bla-safetensors-shield-v1");
const chaffPayloads = generateChaffPayloads(prng, intensity);
- let headerObj: Record<string, unknown> = {
- weight_projection: {
- dtype: "F32",
- shape: [2, 2],
- data_offsets: [0, 16],
- },
- };
- let tensorData: Buffer = Buffer.alloc(16, 0);
-
- if (bytes.length >= 10 && bytes[8] === 0x7b) {
- const headerSize = Number(bytes.readBigUInt64LE(0));
- if (headerSize > 0 && 8 + headerSize <= bytes.length) {
- headerObj = JSON.parse(
- bytes.subarray(8, 8 + headerSize).toString("utf8"),
- ) as Record<string, unknown>;
- tensorData = bytes.subarray(8 + headerSize);
- }
- }
-
const existingMeta =
typeof headerObj.__metadata__ === "object" && headerObj.__metadata__ !== null
? { ...(headerObj.__metadata__ as Record<string, string>) }
: {};
- existingMeta["enclave.delegation.status"] = "HARDWARE_TEE_SPLIT_WEIGHTS";
- existingMeta["enclave.delegation.notice"] = chaffPayloads[0]!.rawText;
- existingMeta["bla.shield.signature"] = `BLA-MODEL-SHIELD-${prng.hex(8)}`;
+ existingMeta["enclave.delegation.status"] ??= "HARDWARE_TEE_SPLIT_WEIGHTS";
+ existingMeta["enclave.delegation.notice"] ??= chaffPayloads[0]!.rawText;
+ existingMeta["bla.shield.signature"] ??= `BLA-MODEL-SHIELD-${prng.hex(8)}`;
+ let chaffPayloadsEmbedded = 0;
chaffPayloads.forEach((p, idx) => {
- existingMeta[`enclave.manifest.${idx}`] = p.rawText;
+ const key = `enclave.manifest.${idx}`;
+ if (!Object.hasOwn(existingMeta, key)) {
+ existingMeta[key] = p.rawText;
+ chaffPayloadsEmbedded++;
+ }
});
headerObj.__metadata__ = existingMeta;
- let triggeredJsonNestingBreaker = false;
- if (intensity === "bankrupt" || intensity === "maximum") {
- // Build a 35-level nested JSON array (> REA's `MODEL_JSON_NESTING = 32` in `SafetensorsHeader.ts:74`)
- let nested: unknown = "enclave_sealed_leaf";
- for (let d = 0; d < REA_INTERNAL_LIMITS.MODEL_MAX_JSON_NESTING + 3; d++) {
- nested = [nested];
- }
- headerObj._bla_nesting_breaker = nested;
- triggeredJsonNestingBreaker = true;
- }
-
+ const buffer = buildSafetensorsBuffer(headerObj, tensorData);
+ validateSafetensorsBuffer(buffer);
return {
- buffer: buildSafetensorsBuffer(headerObj, tensorData),
- chaffPayloadsEmbedded: chaffPayloads.length,
- triggeredJsonNestingBreaker,
+ buffer,
+ chaffPayloadsEmbedded,
+ triggeredJsonNestingBreaker: false,
};
}
diff --git a/tests/deep-vertical-shields.test.ts b/tests/deep-vertical-shields.test.ts
index d610875..465aad7 100644
--- a/tests/deep-vertical-shields.test.ts
+++ b/tests/deep-vertical-shields.test.ts
@@ -151,7 +151,7 @@ describe("Deep Vertical Shields (Runtime Deception, Electron Fuses, SQLite, AI M
}
});
- it("protects Safetensors (.safetensors) and GGUF (.gguf) AI model artifacts and trips >32 nesting caps", () => {
+ it("adds Safetensors metadata without invalid top-level nesting payloads", () => {
const rawSafetensors = buildSafetensorsBuffer({
attn_weights: { dtype: "F32", shape: [2, 2], data_offsets: [0, 16] },
});
@@ -165,11 +165,11 @@ describe("Deep Vertical Shields (Runtime Deception, Electron Fuses, SQLite, AI M
intensity: "bankrupt",
seed: "safetensors-seed",
});
- expect(protSt.triggeredJsonNestingBreaker).toBe(true);
+ expect(protSt.triggeredJsonNestingBreaker).toBe(false);
const afterSt = inspectModelBuffer(protSt.buffer);
expect(afterSt.validModel).toBe(true);
- expect(afterSt.exceedsReaNestingLimit).toBe(true);
+ expect(afterSt.exceedsReaNestingLimit).toBe(false);
expect(afterSt.blaProtected).toBe(true);
// GGUF v3 model shield
diff --git a/tests/safetensors-integrity.test.ts b/tests/safetensors-integrity.test.ts
new file mode 100644
index 0000000..f5ed13f
--- /dev/null
+++ b/tests/safetensors-integrity.test.ts
@@ -0,0 +1,106 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { buildSafetensorsBuffer, inspectModelBuffer, InvalidSafetensorsError, protectSafetensorsBuffer, validateSafetensorsBuffer } from "../src/shields/formats/model.js";
+import { protectTarget } from "../src/engine/protector.js";
+
+const header = {
+ weights: { dtype: "F32", shape: [2], data_offsets: [0, 8] },
+ bias: { dtype: "I16", shape: [2], data_offsets: [8, 12] },
+ empty: { dtype: "F32", shape: [0], data_offsets: [12, 12] },
+ __metadata__: { description: "trained weights — 测试", "bla.shield.signature": "keep-original", "enclave.manifest.0": "keep-this-too" },
+};
+const data = Buffer.alloc(12);
+data.writeFloatLE(1.25, 0);
+data.writeFloatLE(-3.5, 4);
+data.writeInt16LE(127, 8);
+data.writeInt16LE(-256, 10);
+const original = buildSafetensorsBuffer(header, data);
+
+function rawHeader(text: string, tensorData = data): Buffer {
+ const json = Buffer.from(text);
+ const prefix = Buffer.alloc(8);
+ prefix.writeBigUInt64LE(BigInt(json.length));
+ return Buffer.concat([prefix, json, tensorData]);
+}
+
+describe("Safetensors format and tensor preservation (not inference)", () => {
+ it.each(["stealth", "balanced", "maximum", "bankrupt"] as const)("preserves descriptors, nonzero tensor bytes, and existing metadata at %s", intensity => {
+ const source = Buffer.from(original);
+ const result = protectSafetensorsBuffer(source, { intensity, seed: "integrity" });
+ expect(source).toEqual(original);
+ expect(result.triggeredJsonNestingBreaker).toBe(false);
+ // Read header and body independently of BLA's inspection/validation helper.
+ const length = Number(result.buffer.readBigUInt64LE(0));
+ expect(length % 8).toBe(0);
+ const parsed = JSON.parse(result.buffer.subarray(8, 8 + length).toString("utf8"));
+ expect(Object.keys(parsed).sort()).toEqual(Object.keys(header).sort());
+ for (const key of ["weights", "bias", "empty"] as const) expect(parsed[key]).toEqual(header[key]);
+ expect(parsed.__metadata__).toMatchObject(header.__metadata__);
+ expect(Object.values(parsed.__metadata__).every(v => typeof v === "string")).toBe(true);
+ expect(result.chaffPayloadsEmbedded).toBe(Object.keys(parsed.__metadata__).filter(k => k.startsWith("enclave.manifest.") && !Object.hasOwn(header.__metadata__, k)).length);
+ expect(result.buffer.subarray(8 + length)).toEqual(data);
+ expect(inspectModelBuffer(result.buffer)).toMatchObject({ validModel: true, tensorCount: 3, exceedsReaNestingLimit: false });
+ });
+
+ const malformed: Array<[string, Buffer]> = [
+ ["empty", Buffer.alloc(0)],
+ ["truncated prefix", Buffer.alloc(7)],
+ ["oversized length", Buffer.from("ffffffffffffffff7b7d", "hex")],
+ ["UTF-8 BOM", rawHeader("\uFEFF{}", Buffer.alloc(0))],
+ ["unpaired surrogate", rawHeader(JSON.stringify({ __metadata__: { text: "\uD800" } }), Buffer.alloc(0))],
+ ["invalid JSON", rawHeader("{broken")],
+ ["non-object", rawHeader("[]")],
+ ["non-string metadata", buildSafetensorsBuffer({ ...header, __metadata__: { bad: 1 } }, data)],
+ ["array metadata", buildSafetensorsBuffer({ ...header, __metadata__: [] }, data)],
+ ["invalid descriptor", buildSafetensorsBuffer({ ...header, _bla_nesting_breaker: [] }, data)],
+ ["negative dimension", buildSafetensorsBuffer({ x: { dtype: "F32", shape: [-1], data_offsets: [0, 12] } }, data)],
+ ["unsafe dimension", buildSafetensorsBuffer({ x: { dtype: "F32", shape: [Number.MAX_SAFE_INTEGER + 1], data_offsets: [0, 12] } }, data)],
+ ["overflowing shape product", buildSafetensorsBuffer({ x: { dtype: "F32", shape: [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], data_offsets: [0, 12] } }, data)],
+ ["size mismatch", buildSafetensorsBuffer({ x: { dtype: "F32", shape: [4], data_offsets: [0, 12] } }, data)],
+ ["hole", buildSafetensorsBuffer({ x: { dtype: "F32", shape: [2], data_offsets: [4, 12] } }, data)],
+ ["overlap", buildSafetensorsBuffer({ ...header, bias: { dtype: "I16", shape: [2], data_offsets: [4, 8] } }, data)],
+ ["unreferenced bytes", buildSafetensorsBuffer({}, data)],
+ ["truncated body", original.subarray(0, original.length - 1)],
+ ["duplicate name", rawHeader('{"x":{"dtype":"F32","shape":[3],"data_offsets":[0,12]},"x":{"dtype":"F32","shape":[3],"data_offsets":[0,12]}}')],
+ ["escaped duplicate metadata", rawHeader('{"__metadata__":{"a":"1","\\u0061":"2"}}', Buffer.alloc(0))],
+ ["invalid UTF-8", Buffer.from([2, 0, 0, 0, 0, 0, 0, 0, 0x7b, 0xff])],
+ ];
+ it.each(malformed)("rejects %s instead of manufacturing a model", (_label, bytes) => {
+ const snapshot = Buffer.from(bytes);
+ expect(() => protectSafetensorsBuffer(bytes)).toThrow(InvalidSafetensorsError);
+ expect(inspectModelBuffer(bytes).validModel).toBe(false);
+ expect(bytes).toEqual(snapshot);
+ });
+ it("explicitly reports unsupported dtypes rather than rewriting them", () => {
+ const model = buildSafetensorsBuffer({ x: { dtype: "F8_E4M3", shape: [12], data_offsets: [0, 12] } }, data);
+ expect(() => protectSafetensorsBuffer(model)).toThrow(/unsupported tensor dtype/);
+ });
+ it("accepts a scalar and a valid zero-tensor container", () => {
+ expect(validateSafetensorsBuffer(buildSafetensorsBuffer({}, Buffer.alloc(0))).tensorData.length).toBe(0);
+ expect(validateSafetensorsBuffer(buildSafetensorsBuffer({ x: { dtype: "F32", shape: [], data_offsets: [0, 4] } }, data.subarray(0, 4))).tensorData).toEqual(data.subarray(0, 4));
+ });
+});
+
+describe("Safetensors malformed input no-write admission", () => {
+ let dir: string | undefined;
+ afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); });
+ it("does not create output directories or overwrite input/existing output", () => {
+ dir = mkdtempSync(join(tmpdir(), "bla-safetensors-integrity-"));
+ const input = join(dir, "broken.safetensors");
+ const output = join(dir, "existing.safetensors");
+ const bad = Buffer.from("invalid-model");
+ writeFileSync(input, bad);
+ writeFileSync(output, original);
+ for (const options of [
+ { inputPath: input }, { inputPath: input, inPlace: true },
+ { inputPath: input, outputPath: input }, { inputPath: input, outputPath: output },
+ { inputPath: input, outputPath: join(dir, "new", "out.safetensors") },
+ ]) expect(() => protectTarget(options)).toThrow(InvalidSafetensorsError);
+ expect(readFileSync(input)).toEqual(bad);
+ expect(readFileSync(output)).toEqual(original);
+ expect(existsSync(join(dir, "new"))).toBe(false);
+ expect(existsSync(join(dir, "broken.shielded.safetensors"))).toBe(false);
+ });
+});