import { describe, expect, it } from "vitest"; import { __test } from "../index.ts"; const secret = "sk-or-v1-" + "a".repeat(64); describe("leaks bounded traversal and failure behavior", () => { it("deep redaction copies objects and preserves cycles", () => { const source: { text: string; self?: unknown; nested: { list: unknown[] }; } = { text: secret, nested: { list: [secret] }, }; source.self = source; const engine = new __test.LeaksEngine(); const result = engine.redactDeep(source, "provider"); expect(result.changed).toBe(true); expect(result.count).toBe(2); expect(result.value).not.toBe(source); expect(result.value.self).toBe(result.value); expect(result.value.text).not.toBe(secret); expect(source.text).toBe(secret); }); it("passes through primitive and callable values", () => { const engine = new __test.LeaksEngine(); for (const value of [1, true, null, 1n, Symbol.for("x"), () => 1]) { expect(engine.redactDeep(value, "provider")).toMatchObject({ value, changed: false, count: 0, }); } }); it("caps traversal depth at 64 and warns once", () => { const root: Record = {}; let current = root; for (let index = 0; index < 70; index++) { current.next = {}; current = current.next as Record; } current.text = secret; const engine = new __test.LeaksEngine(); const result = engine.redactDeep(root, "provider"); expect(result.count).toBe(0); expect(engine.stats().warnings.map((warning) => warning.code)).toContain( "traversal.depth", ); expect( engine .stats() .warnings.filter((warning) => warning.code === "traversal.depth"), ).toHaveLength(1); }); it("restores deeply without mutating originals", () => { const engine = new __test.LeaksEngine(); const placeholder = engine.redactText(secret, "provider").text; const source = { args: [placeholder] }; const restored = engine.restoreDeep(source); expect(restored.value.args[0]).toBe(secret); expect(source.args[0]).toBe(placeholder); expect(restored.count).toBe(1); }); it("keeps precompiled rule counts stable", () => { const engine = new __test.LeaksEngine(); const before = engine.stats().builtInRuleCount; for (let index = 0; index < 50; index++) engine.redactText(secret, "provider"); expect(engine.stats().builtInRuleCount).toBe(before); expect(__test.builtinRules).toHaveLength(before); }); it("detector throws fail open and warn once", () => { const engine = new __test.LeaksEngine({ detectors: [ () => { throw new Error("boom"); }, ], }); engine.redactText(secret, "provider"); engine.redactText(secret, "provider"); expect( engine .stats() .warnings.filter((warning) => warning.code === "detector.failure"), ).toHaveLength(1); }); });