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.

feat(engine): integrity coverage matrix + refuse predicates

qybaihe0d79799797c7
diff --git a/src/engine/integrity-coverage.ts b/src/engine/integrity-coverage.ts
new file mode 100644
index 0000000..d6c9ff0
--- /dev/null
+++ b/src/engine/integrity-coverage.ts
@@ -0,0 +1,339 @@
+/**
+ * Interleaved integrity coverage matrix (Direction-3).
+ *
+ * Hash-only topology for multi-checker self-seal / sidecar entanglement.
+ * Packaging gates refuse bankrupt when the matrix fails the four predicates
+ * below β€” no probabilistic claims, no forged lint.
+ *
+ * Schema: bla-integrity-coverage/v1
+ */
+
+import { createHash } from "node:crypto";
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+export const INTEGRITY_COVERAGE_SCHEMA = "bla-integrity-coverage/v1" as const;
+
+export interface CoverageMatrix {
+ readonly schema: typeof INTEGRITY_COVERAGE_SCHEMA;
+ /** Protected artifact paths (and optional colocated checker site ids). */
+ readonly nodes: readonly string[];
+ /** checker id β†’ nodes that checker verifies (SHA-256 hard-fail targets). */
+ readonly edges: Readonly<Record<string, readonly string[]>>;
+ /** node β†’ build-time SHA-256 hex (64 lowercase hex). */
+ readonly expectedSha256: Readonly<Record<string, string>>;
+}
+
+export type CoverageRefuseReason =
+ | "uncovered-node"
+ | "checker-not-covered"
+ | "missing-hash"
+ | "invalid-hash"
+ | "disconnected"
+ | "no-checkers";
+
+export interface CoverageEvaluation {
+ readonly schema: typeof INTEGRITY_COVERAGE_SCHEMA;
+ readonly ok: boolean;
+ readonly shouldRefuseBankrupt: boolean;
+ readonly reasons: readonly CoverageRefuseReason[];
+ readonly uncoveredNodes: readonly string[];
+ readonly uncoveredCheckers: readonly string[];
+ readonly missingHashNodes: readonly string[];
+ readonly invalidHashNodes: readonly string[];
+ readonly checkerCount: number;
+ readonly oneLineAdvice: string;
+}
+
+const HEX64 = /^[0-9a-f]{64}$/;
+
+function uniqueSorted(xs: readonly string[]): string[] {
+ return [...new Set(xs)].sort();
+}
+
+/** Weakly connected: treat edges as undirected for the connectivity warning. */
+function isWeaklyConnected(
+ nodes: readonly string[],
+ edges: Readonly<Record<string, readonly string[]>>,
+): boolean {
+ if (nodes.length <= 1) return true;
+ const adj = new Map<string, Set<string>>();
+ for (const n of nodes) adj.set(n, new Set());
+ for (const [c, targets] of Object.entries(edges)) {
+ if (!adj.has(c)) adj.set(c, new Set());
+ for (const t of targets) {
+ if (!adj.has(t)) adj.set(t, new Set());
+ adj.get(c)!.add(t);
+ adj.get(t)!.add(c);
+ }
+ }
+ const start = nodes[0]!;
+ const seen = new Set<string>();
+ const stack = [start];
+ while (stack.length) {
+ const cur = stack.pop()!;
+ if (seen.has(cur)) continue;
+ seen.add(cur);
+ for (const nxt of adj.get(cur) ?? []) {
+ if (!seen.has(nxt)) stack.push(nxt);
+ }
+ }
+ return nodes.every((n) => seen.has(n));
+}
+
+/**
+ * Refuse predicates (bankrupt):
+ * 1. Full coverage β€” every node is listed in at least one edge's targets
+ * 2. Anti-single-point β€” every checker id is itself covered by a *different* checker
+ * 3. Hash completeness β€” every node has a 64-hex expectedSha256
+ * 4. Connectivity β€” undirected coverage graph is weakly connected (else refuse)
+ */
+export function evaluateCoverageMatrix(matrix: CoverageMatrix): CoverageEvaluation {
+ const nodes = uniqueSorted(matrix.nodes ?? []);
+ const edges = matrix.edges ?? {};
+ const checkers = uniqueSorted(Object.keys(edges));
+ const expected = matrix.expectedSha256 ?? {};
+
+ const covered = new Set<string>();
+ for (const targets of Object.values(edges)) {
+ for (const t of targets) covered.add(t);
+ }
+
+ const uncoveredNodes = nodes.filter((n) => !covered.has(n));
+ const uncoveredCheckers = checkers.filter((c) => {
+ // Covered by a different checker.
+ for (const [other, targets] of Object.entries(edges)) {
+ if (other === c) continue;
+ if (targets.includes(c)) return false;
+ }
+ return true;
+ });
+
+ const missingHashNodes: string[] = [];
+ const invalidHashNodes: string[] = [];
+ for (const n of nodes) {
+ const h = expected[n];
+ if (h === undefined || h === "") {
+ missingHashNodes.push(n);
+ } else if (!HEX64.test(h.toLowerCase())) {
+ invalidHashNodes.push(n);
+ }
+ }
+
+ const reasons: CoverageRefuseReason[] = [];
+ if (checkers.length === 0) reasons.push("no-checkers");
+ if (uncoveredNodes.length > 0) reasons.push("uncovered-node");
+ if (uncoveredCheckers.length > 0) reasons.push("checker-not-covered");
+ if (missingHashNodes.length > 0) reasons.push("missing-hash");
+ if (invalidHashNodes.length > 0) reasons.push("invalid-hash");
+
+ // Connectivity over the union of nodes βˆͺ checker ids.
+ const connNodes = uniqueSorted([...nodes, ...checkers]);
+ const connected = isWeaklyConnected(connNodes, edges);
+ if (!connected) reasons.push("disconnected");
+
+ const ok = reasons.length === 0;
+ const advice = ok
+ ? "Integrity coverage matrix satisfies full coverage, anti-single-point, hashes, and connectivity."
+ : `ERROR: Integrity coverage refuse [${reasons.join(", ")}]. ` +
+ `Need β‰₯2 interleaved checkers that cover each other and every node, with sha256 hex for each node.`;
+
+ return {
+ schema: INTEGRITY_COVERAGE_SCHEMA,
+ ok,
+ shouldRefuseBankrupt: !ok,
+ reasons,
+ uncoveredNodes,
+ uncoveredCheckers,
+ missingHashNodes,
+ invalidHashNodes,
+ checkerCount: checkers.length,
+ oneLineAdvice: advice,
+ };
+}
+
+export interface BuildCoverageOptions {
+ /** File paths under protection. */
+ readonly fileNodes: readonly string[];
+ /**
+ * Checker host paths (JS modules that can run sha256). When fewer than 2,
+ * colocated virtual sites `${host}#site0` / `#site1` are synthesized on the
+ * first host so anti-single-point is expressible without a second file.
+ */
+ readonly checkerHosts: readonly string[];
+ /** Build-time hashes for file nodes (and optional virtual checker sites). */
+ readonly expectedSha256: Readonly<Record<string, string>>;
+ /** How many colocated sites to emit when only one host (default 2). */
+ readonly colocatedSites?: number;
+}
+
+/**
+ * Build a ring/colocated coverage matrix.
+ * - β‰₯2 hosts: ring β€” host[i] covers host[i+1] plus every file node.
+ * - 1 host: colocated sites host#site0 / host#site1 covering each other + files.
+ */
+export function buildInterleavedCoverageMatrix(
+ options: BuildCoverageOptions,
+): CoverageMatrix {
+ const fileNodes = uniqueSorted(options.fileNodes.filter((p) => p.length > 0));
+ const hosts = uniqueSorted(options.checkerHosts.filter((p) => p.length > 0));
+ const expectedSha256: Record<string, string> = {};
+ for (const [k, v] of Object.entries(options.expectedSha256 ?? {})) {
+ if (typeof v === "string" && HEX64.test(v.toLowerCase())) {
+ expectedSha256[k] = v.toLowerCase();
+ }
+ }
+
+ const edges: Record<string, string[]> = {};
+ let nodes: string[] = [...fileNodes];
+
+ if (hosts.length >= 2) {
+ for (let i = 0; i < hosts.length; i++) {
+ const me = hosts[i]!;
+ const peer = hosts[(i + 1) % hosts.length]!;
+ const targets = uniqueSorted([...fileNodes, peer]);
+ edges[me] = targets;
+ }
+ nodes = uniqueSorted([...fileNodes, ...hosts]);
+ } else if (hosts.length === 1) {
+ const host = hosts[0]!;
+ const nSites = Math.max(2, options.colocatedSites ?? 2);
+ const sites: string[] = [];
+ for (let i = 0; i < nSites; i++) sites.push(`${host}#site${i}`);
+ for (let i = 0; i < sites.length; i++) {
+ const me = sites[i]!;
+ const peer = sites[(i + 1) % sites.length]!;
+ edges[me] = uniqueSorted([...fileNodes, peer]);
+ }
+ nodes = uniqueSorted([...fileNodes, ...sites]);
+ // Virtual checker sites inherit the host file hash when available.
+ const hostHash = expectedSha256[host];
+ if (hostHash) {
+ for (const s of sites) expectedSha256[s] = hostHash;
+ }
+ }
+
+ return {
+ schema: INTEGRITY_COVERAGE_SCHEMA,
+ nodes,
+ edges,
+ expectedSha256,
+ };
+}
+
+export function sha256Hex(buf: Buffer | string): string {
+ return createHash("sha256").update(buf).digest("hex");
+}
+
+/**
+ * After checker hosts are written, fill expectedSha256 for file nodes and any
+ * colocated virtual sites (`path#siteN` inherits the host file digest).
+ */
+export function finalizeCoverageMatrixHashes(
+ matrix: CoverageMatrix,
+ fileBytes: Readonly<Record<string, Buffer | string>>,
+): CoverageMatrix {
+ const expectedSha256: Record<string, string> = { ...matrix.expectedSha256 };
+ for (const [path, bytes] of Object.entries(fileBytes)) {
+ const hex = sha256Hex(typeof bytes === "string" ? Buffer.from(bytes) : bytes);
+ expectedSha256[path] = hex;
+ }
+ for (const node of matrix.nodes) {
+ const hashIdx = node.indexOf("#site");
+ if (hashIdx > 0) {
+ const host = node.slice(0, hashIdx);
+ if (expectedSha256[host]) expectedSha256[node] = expectedSha256[host]!;
+ }
+ }
+ return {
+ schema: INTEGRITY_COVERAGE_SCHEMA,
+ nodes: matrix.nodes,
+ edges: matrix.edges,
+ expectedSha256,
+ };
+}
+
+
+
+const MATRIX_NAMES = new Set([
+ "integrity-coverage.json",
+ ".bla-integrity-coverage.json",
+]);
+
+export interface IntegrityCoverageFileReport extends CoverageEvaluation {
+ readonly path: string;
+ readonly matrix: CoverageMatrix | null;
+ readonly parseError?: string;
+}
+
+/**
+ * Discover integrity-coverage.json artifacts under a project tree and evaluate
+ * each. Missing matrices are not findings β€” only present-but-failing matrices
+ * refuse bankrupt (migration-safe).
+ */
+export function discoverAndLintIntegrityCoverage(
+ directory: string,
+): IntegrityCoverageFileReport[] {
+ const abs = resolve(directory);
+ const out: IntegrityCoverageFileReport[] = [];
+ const stack: { dir: string; depth: number }[] = [{ dir: abs, depth: 0 }];
+ let files = 0;
+ while (stack.length && files < 32) {
+ const { dir, depth } = stack.pop()!;
+ if (depth > 5) continue;
+ let entries: string[] = [];
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ continue;
+ }
+ for (const name of entries) {
+ if (name === "node_modules" || name === ".git") continue;
+ const full = join(dir, name);
+ let st;
+ try {
+ st = statSync(full);
+ } catch {
+ continue;
+ }
+ if (st.isDirectory()) {
+ stack.push({ dir: full, depth: depth + 1 });
+ continue;
+ }
+ if (!MATRIX_NAMES.has(name)) continue;
+ files += 1;
+ try {
+ const raw = JSON.parse(readFileSync(full, "utf8")) as CoverageMatrix;
+ const ev = evaluateCoverageMatrix(raw);
+ out.push({ ...ev, path: full, matrix: raw });
+ } catch (err) {
+ out.push({
+ schema: INTEGRITY_COVERAGE_SCHEMA,
+ ok: false,
+ shouldRefuseBankrupt: true,
+ reasons: ["invalid-hash"],
+ uncoveredNodes: [],
+ uncoveredCheckers: [],
+ missingHashNodes: [],
+ invalidHashNodes: [],
+ checkerCount: 0,
+ oneLineAdvice: "ERROR: integrity-coverage.json is not valid bla-integrity-coverage/v1 JSON.",
+ path: full,
+ matrix: null,
+ parseError: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ }
+ return out;
+}
+
+export function integrityCoverageRefuseMessage(
+ report: IntegrityCoverageFileReport,
+ pathLabel: string,
+): string {
+ return (
+ `Refusing integrity-coverage gate at ${pathLabel} [${report.reasons.join(", ")}]. ` +
+ report.oneLineAdvice
+ );
+}
diff --git a/tests/integrity-coverage.test.ts b/tests/integrity-coverage.test.ts
new file mode 100644
index 0000000..d35c234
--- /dev/null
+++ b/tests/integrity-coverage.test.ts
@@ -0,0 +1,157 @@
+import { describe, expect, it } from "vitest";
+import { createHash } from "node:crypto";
+import { mkdtempSync, writeFileSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { spawnSync } from "node:child_process";
+import { SeededPrng } from "../src/core/prng.js";
+import {
+ INTEGRITY_COVERAGE_SCHEMA,
+ buildInterleavedCoverageMatrix,
+ evaluateCoverageMatrix,
+ finalizeCoverageMatrixHashes,
+} from "../src/engine/integrity-coverage.js";
+import { generateSelfSealSnippet } from "../src/shields/runtime/self-seal.js";
+
+function sha(s: string): string {
+ return createHash("sha256").update(s).digest("hex");
+}
+
+describe("integrity coverage matrix (Direction-3)", () => {
+ it("ring of 2 JS hosts + payload satisfies all refuse predicates", () => {
+ const files = {
+ "license.cjs": "entry",
+ "peer.cjs": "peer",
+ "panel.html": "<html/>",
+ "core.wasm": "wasm",
+ };
+ const expectedSha256 = Object.fromEntries(
+ Object.entries(files).map(([k, v]) => [k, sha(v)]),
+ );
+ const matrix = buildInterleavedCoverageMatrix({
+ fileNodes: Object.keys(files),
+ checkerHosts: ["license.cjs", "peer.cjs"],
+ expectedSha256,
+ });
+ expect(matrix.schema).toBe(INTEGRITY_COVERAGE_SCHEMA);
+ const ev = evaluateCoverageMatrix(matrix);
+ expect(ev.ok).toBe(true);
+ expect(ev.shouldRefuseBankrupt).toBe(false);
+ expect(ev.checkerCount).toBe(2);
+ });
+
+ it("colocated sites on one host pass anti-single-point after finalize", () => {
+ const host = "license.cjs";
+ const files: Record<string, string> = {
+ [host]: "module.exports=1",
+ "panel.html": "<p/>",
+ "core.wasm": "\0wasm",
+ };
+ let matrix = buildInterleavedCoverageMatrix({
+ fileNodes: Object.keys(files),
+ checkerHosts: [host],
+ expectedSha256: {},
+ colocatedSites: 2,
+ });
+ matrix = finalizeCoverageMatrixHashes(
+ matrix,
+ Object.fromEntries(Object.entries(files).map(([k, v]) => [k, Buffer.from(v)])),
+ );
+ const ev = evaluateCoverageMatrix(matrix);
+ expect(ev.ok).toBe(true);
+ expect(ev.uncoveredCheckers).toEqual([]);
+ });
+
+ it("refuses single-checker topology (anti-single-point)", () => {
+ const matrix = {
+ schema: INTEGRITY_COVERAGE_SCHEMA,
+ nodes: ["a.js", "b.wasm"],
+ edges: { "a.js": ["b.wasm"] },
+ expectedSha256: { "a.js": sha("a"), "b.wasm": sha("b") },
+ };
+ const ev = evaluateCoverageMatrix(matrix);
+ expect(ev.ok).toBe(false);
+ expect(ev.reasons).toContain("checker-not-covered");
+ expect(ev.shouldRefuseBankrupt).toBe(true);
+ });
+
+ it("refuses missing hashes", () => {
+ const matrix = buildInterleavedCoverageMatrix({
+ fileNodes: ["a.js", "b.js", "c.wasm"],
+ checkerHosts: ["a.js", "b.js"],
+ expectedSha256: { "a.js": sha("a") },
+ });
+ const ev = evaluateCoverageMatrix(matrix);
+ expect(ev.reasons).toContain("missing-hash");
+ expect(ev.shouldRefuseBankrupt).toBe(true);
+ });
+
+ it("interleaved self-seal hard-fails when a sibling is tampered", () => {
+ const dir = mkdtempSync(join(tmpdir(), "bla-intcov-"));
+ const sib = join(dir, "asset.bin");
+ writeFileSync(sib, "clean-asset");
+ const hex = createHash("sha256").update("clean-asset").digest("hex");
+ const snip = generateSelfSealSnippet(new SeededPrng("intcov-runtime"), {
+ siblingPaths: ["./asset.bin"],
+ expectedSiblingSha256: { "./asset.bin": hex },
+ hardFailOnSiblingMismatch: true,
+ interleavedSites: 2,
+ bindingName: "integrityDigestTest",
+ checkerHostPath: "main.cjs",
+ coverageFileNodes: ["main.cjs", "./asset.bin"],
+ envFingerprint: false,
+ });
+ expect(snip.interleavedSites).toBe(2);
+ expect(snip.code.match(/function /g)?.length).toBeGreaterThanOrEqual(2);
+
+ const main = join(dir, "main.cjs");
+ writeFileSync(
+ main,
+ `"use strict";\n${snip.code}\nconsole.log("ok", integrityDigestTest);\n`,
+ );
+ const ok = spawnSync(process.execPath, [main], { encoding: "utf8" });
+ expect(ok.status).toBe(0);
+ expect(ok.stdout).toContain("ok");
+
+ writeFileSync(sib, "TAMPERED");
+ const bad = spawnSync(process.execPath, [main], { encoding: "utf8" });
+ expect(bad.status).not.toBe(0);
+ expect(String(bad.stderr) + String(bad.stdout)).toMatch(/integrity check failed/);
+ });
+
+ it("deleting one colocated checker site from matrix fails anti-single-point lint", () => {
+ const files = {
+ "license.cjs": "x",
+ "panel.html": "y",
+ };
+ let matrix = buildInterleavedCoverageMatrix({
+ fileNodes: Object.keys(files),
+ checkerHosts: ["license.cjs"],
+ expectedSha256: {},
+ colocatedSites: 2,
+ });
+ matrix = finalizeCoverageMatrixHashes(
+ matrix,
+ Object.fromEntries(Object.entries(files).map(([k, v]) => [k, Buffer.from(v)])),
+ );
+ expect(evaluateCoverageMatrix(matrix).ok).toBe(true);
+
+ // Simulate deleting site1: drop its edge and node.
+ const broken = {
+ ...matrix,
+ nodes: matrix.nodes.filter((n) => n !== "license.cjs#site1"),
+ edges: Object.fromEntries(
+ Object.entries(matrix.edges).filter(([k]) => k !== "license.cjs#site1"),
+ ),
+ };
+ // site0 still targets site1 which is gone from nodes β€” also strip that target
+ broken.edges = {
+ "license.cjs#site0": (matrix.edges["license.cjs#site0"] ?? []).filter(
+ (t) => t !== "license.cjs#site1",
+ ),
+ };
+ const ev = evaluateCoverageMatrix(broken);
+ expect(ev.ok).toBe(false);
+ expect(ev.reasons.length).toBeGreaterThan(0);
+ });
+});