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(sqlite): degrade gracefully when node:sqlite is unavailable

qybaihe9885264e0034
diff --git a/.nvmrc b/.nvmrc
new file mode 100644
index 0000000..2bd5a0a
--- /dev/null
+++ b/.nvmrc
@@ -0,0 +1 @@
+22
diff --git a/src/core/sqlite-runtime.ts b/src/core/sqlite-runtime.ts
index 2fef688..0cdb248 100644
--- a/src/core/sqlite-runtime.ts
+++ b/src/core/sqlite-runtime.ts
@@ -3,23 +3,52 @@ import type { DatabaseSync } from "node:sqlite";
const require = createRequire(import.meta.url);
-/** Load lazily so non-SQLite commands can still explain an unsupported setup. */
-export function getDatabaseSyncClass(): typeof DatabaseSync {
+let cachedAvailable: boolean | undefined;
+let cachedClass: typeof DatabaseSync | null | undefined;
+
+/**
+ * Probe whether the current Node runtime exposes a usable `node:sqlite`
+ * `DatabaseSync` with custom scalar `function()` support (Node ^22.13 || >=24).
+ * Result is memoized for the process lifetime.
+ */
+export function isNodeSqliteAvailable(): boolean {
+ if (cachedAvailable !== undefined) return cachedAvailable;
+ cachedAvailable = tryGetDatabaseSyncClass() !== null;
+ return cachedAvailable;
+}
+
+/**
+ * Load `DatabaseSync` when available; return `null` on unsupported runtimes
+ * (Node < 22.13, `--no-experimental-sqlite`, or missing `function` API).
+ * Prefer this for optional/degraded paths; use `getDatabaseSyncClass()` when
+ * SQLite is required and a clear hard-error is appropriate.
+ */
+export function tryGetDatabaseSyncClass(): typeof DatabaseSync | null {
+ if (cachedClass !== undefined) return cachedClass;
try {
const mod = require("node:sqlite") as { DatabaseSync?: typeof DatabaseSync };
if (
typeof mod.DatabaseSync !== "function" ||
typeof mod.DatabaseSync.prototype?.function !== "function"
) {
- throw new Error("node:sqlite is missing DatabaseSync.function");
+ cachedClass = null;
+ return null;
}
- return mod.DatabaseSync;
- } catch (cause) {
- throw new Error(
- `BLA SQLite support requires Node.js 22.x >=22.13.0 or Node.js >=24.0.0 ` +
- `with node:sqlite enabled (current runtime: ${process.version}). ` +
- "Upgrade Node.js and remove --no-experimental-sqlite if set.",
- { cause },
- );
+ cachedClass = mod.DatabaseSync;
+ return cachedClass;
+ } catch {
+ cachedClass = null;
+ return null;
}
}
+
+/** Load lazily so non-SQLite commands can still explain an unsupported setup. */
+export function getDatabaseSyncClass(): typeof DatabaseSync {
+ const cls = tryGetDatabaseSyncClass();
+ if (cls) return cls;
+ throw new Error(
+ `BLA SQLite support requires Node.js 22.x >=22.13.0 or Node.js >=24.0.0 ` +
+ `with node:sqlite enabled (current runtime: ${process.version}). ` +
+ "Upgrade Node.js and remove --no-experimental-sqlite if set.",
+ );
+}
diff --git a/src/engine/benchmark.ts b/src/engine/benchmark.ts
index 43fdf73..747f953 100644
--- a/src/engine/benchmark.ts
+++ b/src/engine/benchmark.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
import vm from "node:vm";
import { BLA_IDENTITY } from "../identity.js";
import type { BenchmarkReport, ShowcaseCaseResult } from "../core/types.js";
+import { isNodeSqliteAvailable } from "../core/sqlite-runtime.js";
import { packAsarBuffer } from "../shields/formats/asar.js";
import { buildSampleSqliteDatabase } from "../shields/formats/sqlite.js";
import { buildSafetensorsBuffer } from "../shields/formats/model.js";
@@ -292,7 +293,9 @@ export async function runShowcaseBenchmark(): Promise<BenchmarkReport> {
}
// 6. Local SQLite 3 Entitlement Database (.sqlite)
- {
+ // Degrade gracefully on Node < 22.13 / --no-experimental-sqlite: skip this target
+ // rather than hard-failing the entire Counter-REA showcase.
+ if (isNodeSqliteAvailable()) {
const dbPath = join(tempDir, "entitlements.sqlite");
const outDbPath = join(tempDir, "entitlements.shielded.sqlite");
writeFileSync(dbPath, buildSampleSqliteDatabase());
diff --git a/tests/cli-mcp-setup.test.ts b/tests/cli-mcp-setup.test.ts
index 85f1908..d115461 100644
--- a/tests/cli-mcp-setup.test.ts
+++ b/tests/cli-mcp-setup.test.ts
@@ -6,6 +6,7 @@ import { runSetup, runUninstall } from "../src/setup/setup.js";
import { runDoctor } from "../src/setup/doctor.js";
import { handleMcpRequest } from "../src/mcp/server.js";
import { runShowcaseBenchmark } from "../src/engine/benchmark.js";
+import { isNodeSqliteAvailable } from "../src/core/sqlite-runtime.js";
describe("CLI Setup, Doctor, Benchmark & MCP Server", () => {
it("registers and uninstalls BLA MCP server + skill across all 6 AI coding agents in an isolated homeDir", () => {
@@ -35,8 +36,13 @@ describe("CLI Setup, Doctor, Benchmark & MCP Server", () => {
const skillPath = path.join(fakeHome, ".claude", "skills", "blind-llm-agents", "SKILL.md");
expect(fs.existsSync(skillPath)).toBe(true);
- // Run doctor and verify the 6 configured clients report healthy MCP + Skill
- const doctorReport = runDoctor(fakeHome);
+ // Run doctor and verify the 6 configured clients report healthy MCP + Skill.
+ // Override sqlite availability so this assertion isolates MCP/skill registration
+ // from the Node runtime floor (sqlite is probed separately by doctor/engine checks).
+ const doctorReport = runDoctor({
+ homeDir: fakeHome,
+ sqliteAvailableOverride: true,
+ });
expect(doctorReport.healthy).toBe(true);
const configuredClients = doctorReport.agentClients.filter((c) => c.mcpRegistered);
expect(configuredClients.length).toBe(6);
@@ -138,7 +144,7 @@ describe("CLI Setup, Doctor, Benchmark & MCP Server", () => {
}
});
- it("runs the full 8-target Counter-REA benchmark suite and achieves >30x token amplification", async () => {
+ it.skipIf(!isNodeSqliteAvailable())("runs the full 8-target Counter-REA benchmark suite and achieves >30x token amplification", async () => {
const report = await runShowcaseBenchmark();
expect(report.cases.length).toBe(10);
expect(report.cases.every((c) => c.functionalCheckPassed)).toBe(true);
diff --git a/tests/deep-vertical-shields.test.ts b/tests/deep-vertical-shields.test.ts
index 465aad7..650431a 100644
--- a/tests/deep-vertical-shields.test.ts
+++ b/tests/deep-vertical-shields.test.ts
@@ -1,15 +1,9 @@
import { describe, expect, it } from "vitest";
-import { createRequire } from "node:module";
-import type { DatabaseSync as DatabaseSyncType } from "node:sqlite";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import * as vm from "node:vm";
-
-const require = createRequire(import.meta.url);
-const { DatabaseSync } = require("node:sqlite") as {
- DatabaseSync: typeof DatabaseSyncType;
-};
+import { getDatabaseSyncClass, isNodeSqliteAvailable } from "../src/core/sqlite-runtime.js";
import { SeededPrng } from "../src/core/prng.js";
import { generateChaffPayloads } from "../src/shields/chaff/chaff-generator.js";
import { generateRuntimeDeceptionSnippet } from "../src/shields/runtime/runtime-shield.js";
@@ -100,7 +94,8 @@ describe("Deep Vertical Shields (Runtime Deception, Electron Fuses, SQLite, AI M
expect(after.onlyLoadFromAsarEnforced).toBe(true);
});
- it("protects SQLite 3 databases with Honey Tables and Generated Column Traps while keeping original tables readable", () => {
+ it.skipIf(!isNodeSqliteAvailable())("protects SQLite 3 databases with Honey Tables and Generated Column Traps while keeping original tables readable", () => {
+ const DatabaseSync = getDatabaseSyncClass();
const rawSqlite = buildSampleSqliteDatabase();
const beforeInfo = inspectSqliteBuffer(rawSqlite);
expect(beforeInfo.validSqlite).toBe(true);
diff --git a/tests/setup-mcp-doctor-release.test.ts b/tests/setup-mcp-doctor-release.test.ts
index 2942697..3bdb718 100644
--- a/tests/setup-mcp-doctor-release.test.ts
+++ b/tests/setup-mcp-doctor-release.test.ts
@@ -33,6 +33,7 @@ import {
resolveSupportedAgentClients,
} from "../src/setup/clients.js";
import { runDoctor } from "../src/setup/doctor.js";
+import { isNodeSqliteAvailable } from "../src/core/sqlite-runtime.js";
import {
getInstallManifestPath,
readInstallManifest,
@@ -759,6 +760,8 @@ describe("Issue #11: Doctor Real Readiness Checks & Command/Config/Skill/Handsha
const docHealthy = runDoctor({
homeDir: homeHealthy,
verifyHandshake: true,
+ // Isolate MCP/skill/handshake health from the Node sqlite runtime floor.
+ sqliteAvailableOverride: true,
});
expect(docHealthy.healthy).toBe(true);
expect(docHealthy.exitCode).toBe(0);
@@ -855,7 +858,7 @@ describe("Issue #12: Release Version, Tag, Commit & Tarball Consistency + Dual T
expect(retryPlan.shouldPublishAlias).toBe(true);
});
- it("packs both bla-agents and bla-shield tarballs and verifies exports, 3 bin entrypoints, and read-only doctor in clean temp dirs", () => {
+ it.skipIf(!isNodeSqliteAvailable())("packs both bla-agents and bla-shield tarballs and verifies exports, 3 bin entrypoints, and read-only doctor in clean temp dirs", () => {
const outDir = makeTempDir("bla-release-pack-");
const packed = packDualReleaseTarballs(process.cwd(), outDir);
diff --git a/tests/sqlite-coverage-debug-posture.test.ts b/tests/sqlite-coverage-debug-posture.test.ts
index e454ec2..2305dcc 100644
--- a/tests/sqlite-coverage-debug-posture.test.ts
+++ b/tests/sqlite-coverage-debug-posture.test.ts
@@ -3,7 +3,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import vm from "node:vm";
-import { getDatabaseSyncClass } from "../src/core/sqlite-runtime.js";
+import { getDatabaseSyncClass, isNodeSqliteAvailable } from "../src/core/sqlite-runtime.js";
import {
buildSampleSqliteDatabase,
DEFAULT_SQLITE_SENSITIVITY_POLICY,
@@ -38,7 +38,7 @@ describe("Issues #18, #19, #20, #21 — SQLite Consistency/Policy, Debug Posture
// ==========================================================================
// Issue #18: SQLite DB/WAL Consistency Admission
// ==========================================================================
- describe("Issue #18: SQLite DB/WAL consistency validation before protection", () => {
+ describe.skipIf(!isNodeSqliteAvailable())("Issue #18: SQLite DB/WAL consistency validation before protection", () => {
it("rejects uncheckpointed WAL database (both by path and by main-file buffer) instead of dropping committed rows", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-sqlite-wal-repro-"));
tempDirs.push(dir);
@@ -139,7 +139,7 @@ describe("Issues #18, #19, #20, #21 — SQLite Consistency/Policy, Debug Posture
// Issue #21: SQLite Sensitive Data Policy & Confidentiality Separation
// ==========================================================================
describe("Issue #21: SQLite sensitive data exposure policy and decoration vs confidentiality", () => {
- it("reports exposed sensitive columns even when honey tables are present, without leaking secret values in output", () => {
+ it.skipIf(!isNodeSqliteAvailable())("reports exposed sensitive columns even when honey tables are present, without leaking secret values in output", () => {
const rawSqlite = buildSampleSqliteDatabase();
const protectedSqlite = protectSqliteBuffer(rawSqlite, { intensity: "maximum" });
@@ -177,7 +177,7 @@ describe("Issues #18, #19, #20, #21 — SQLite Consistency/Policy, Debug Posture
expect(serialized).not.toContain("tok_live_9988776655");
});
- it("clears policy violations after data minimization while keeping confidentialityState as confidentiality-not-established", () => {
+ it.skipIf(!isNodeSqliteAvailable())("clears policy violations after data minimization while keeping confidentialityState as confidentiality-not-established", () => {
const rawSqlite = buildSampleSqliteDatabase();
const minimized = minimizeSqliteDatabaseBuffer(rawSqlite, [
{ table: "license_cache", column: "offline_token" },
diff --git a/tests/sqlite-runtime.test.ts b/tests/sqlite-runtime.test.ts
index 6dd70a4..6b2aa08 100644
--- a/tests/sqlite-runtime.test.ts
+++ b/tests/sqlite-runtime.test.ts
@@ -2,9 +2,16 @@ import { readFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
-import { getDatabaseSyncClass } from "../src/core/sqlite-runtime.js";
+import {
+ getDatabaseSyncClass,
+ isNodeSqliteAvailable,
+} from "../src/core/sqlite-runtime.js";
const repoRoot = resolve(import.meta.dirname, "..");
+const SQLITE_AVAILABLE = isNodeSqliteAvailable();
+/** `--no-experimental-sqlite` exists only on Node 22+; Node 20 rejects it as a bad option. */
+const SUPPORTS_NO_EXPERIMENTAL_SQLITE_FLAG =
+ Number(process.versions.node.split(".")[0]!) >= 22;
describe("SQLite runtime floor", () => {
it("declares only Node versions where node:sqlite DatabaseSync.function is unflagged", () => {
@@ -16,40 +23,58 @@ describe("SQLite runtime floor", () => {
expect(pkg.engines?.node).toBe("^22.13.0 || >=24.0.0");
});
- it("loads DatabaseSync with custom scalar function support on the supported runtime", () => {
- const DatabaseSync = getDatabaseSyncClass();
- expect(typeof DatabaseSync.prototype.function).toBe("function");
+ it("exposes an availability probe that matches getDatabaseSyncClass success", () => {
+ expect(typeof isNodeSqliteAvailable()).toBe("boolean");
+ if (SQLITE_AVAILABLE) {
+ expect(() => getDatabaseSyncClass()).not.toThrow();
+ } else {
+ expect(() => getDatabaseSyncClass()).toThrow(/BLA SQLite support requires Node/);
+ }
});
- it("Allows non-SQLite CLI commands when node:sqlite is disabled", () => {
- const cli = resolve(repoRoot, "src/cli.ts");
- const result = spawnSync(
- process.execPath,
- ["--no-experimental-sqlite", "--import", "tsx", cli, "--version"],
- { cwd: repoRoot, encoding: "utf8" },
- );
- expect(result.status).toBe(0);
- expect(result.stdout.trim()).toMatch(/^\d+\.\d+\.\d+$/);
- });
+ it.skipIf(!SQLITE_AVAILABLE)(
+ "loads DatabaseSync with custom scalar function support on the supported runtime",
+ () => {
+ const DatabaseSync = getDatabaseSyncClass();
+ expect(typeof DatabaseSync.prototype.function).toBe("function");
+ },
+ );
- it("Reports a clear Node runtime requirement when SQLite protection runs without node:sqlite", () => {
- const script =
- "import { buildSampleSqliteDatabase } from './src/shields/formats/sqlite.ts'; buildSampleSqliteDatabase();";
- const result = spawnSync(
- process.execPath,
- [
- "--no-experimental-sqlite",
- "--import",
- "tsx",
- "--input-type=module",
- "-e",
- script,
- ],
- { cwd: repoRoot, encoding: "utf8" },
- );
- expect(result.status).not.toBe(0);
- expect(result.stderr).toContain(
- "BLA SQLite support requires Node.js 22.x >=22.13.0 or Node.js >=24.0.0",
- );
- });
+ it.skipIf(!SUPPORTS_NO_EXPERIMENTAL_SQLITE_FLAG)(
+ "Allows non-SQLite CLI commands when node:sqlite is disabled",
+ () => {
+ const cli = resolve(repoRoot, "src/cli.ts");
+ const result = spawnSync(
+ process.execPath,
+ ["--no-experimental-sqlite", "--import", "tsx", cli, "--version"],
+ { cwd: repoRoot, encoding: "utf8" },
+ );
+ expect(result.status).toBe(0);
+ expect(result.stdout.trim()).toMatch(/^\d+\.\d+\.\d+$/);
+ },
+ );
+
+ it.skipIf(!SUPPORTS_NO_EXPERIMENTAL_SQLITE_FLAG)(
+ "Reports a clear Node runtime requirement when SQLite protection runs without node:sqlite",
+ () => {
+ const script =
+ "import { buildSampleSqliteDatabase } from './src/shields/formats/sqlite.ts'; buildSampleSqliteDatabase();";
+ const result = spawnSync(
+ process.execPath,
+ [
+ "--no-experimental-sqlite",
+ "--import",
+ "tsx",
+ "--input-type=module",
+ "-e",
+ script,
+ ],
+ { cwd: repoRoot, encoding: "utf8" },
+ );
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toContain(
+ "BLA SQLite support requires Node.js 22.x >=22.13.0 or Node.js >=24.0.0",
+ );
+ },
+ );
});