🛡️ 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.
JavaScript adversarial-aiclaude-codecursorelectron-securityllm-securitymcpmcp-serverobfuscationreverse-engineeringwebassembly
fix(sqlite,coverage,runtime): enforce SQLite DB/WAL consistency, sensitive column policy, debug posture checks, and server authorization contract (Fixes #18, Fixes #19, Fixes #20, Fixes #21)
qybaihebce9519e3903
diff --git a/src/core/coverage-contract.ts b/src/core/coverage-contract.tsnew file mode 100644index 0000000..3fae5b6--- /dev/null+++ b/src/core/coverage-contract.ts@@ -0,0 +1,282 @@+import { createHash, randomBytes } from "node:crypto";++export type ClientArtifactCoverageStatus =+ | "assessed-static-and-heuristic-cost-amplification"+ | "not-protected";++export type ServerAuthorizationCoverageStatus =+ | "not-assessed/external-control-required"+ | "verified-local-reference-fixture";++export interface ThreatPremiseBoundary {+ readonly id:+ | "authenticated-low-privilege-session"+ | "controlled-client-same-origin-fetch"+ | "authorized-user-response-observation";+ readonly coveredByClientArtifactShield: false;+ readonly authoritativeControlLocation: "server-side-application";+ readonly explanation: string;+}++export interface DefenseCoverageContract {+ readonly clientArtifact: {+ readonly status: ClientArtifactCoverageStatus;+ readonly scope: "static-reverse-engineering-and-automated-inspection-friction";+ readonly guaranteesConfidentialityOfShippedData: false;+ readonly enforcesAccessControl: false;+ };+ readonly serverAuthorization: {+ readonly status: ServerAuthorizationCoverageStatus;+ readonly responsibility: "external-application-backend";+ readonly summary: string;+ };+ readonly threatPremises: readonly ThreatPremiseBoundary[];+}++export function buildDefenseCoverageContract(options?: {+ readonly clientProtected?: boolean;+ readonly localServerFixtureVerified?: boolean;+}): DefenseCoverageContract {+ const clientProtected = options?.clientProtected ?? true;+ const serverVerified = options?.localServerFixtureVerified ?? false;++ return {+ clientArtifact: {+ status: clientProtected+ ? "assessed-static-and-heuristic-cost-amplification"+ : "not-protected",+ scope: "static-reverse-engineering-and-automated-inspection-friction",+ guaranteesConfidentialityOfShippedData: false,+ enforcesAccessControl: false,+ },+ serverAuthorization: {+ status: serverVerified+ ? "verified-local-reference-fixture"+ : "not-assessed/external-control-required",+ responsibility: "external-application-backend",+ summary: serverVerified+ ? "Verified against local synthetic multi-tenant reference fixture only; production backends must enforce per-request identity, object/tenant authorization, session revocation, and response data minimization independently."+ : "Server-side authentication, object/tenant authorization, session invalidation, and CSRF/replay controls are outside BLA client-artifact scope and must be enforced by the backend service.",+ },+ threatPremises: [+ {+ id: "authenticated-low-privilege-session",+ coveredByClientArtifactShield: false,+ authoritativeControlLocation: "server-side-application",+ explanation:+ "An active browser scenario (e.g., Playwright same-origin fetch) can reuse an existing low-privilege session cookie/token. Hiding UI buttons or obfuscating client bundles does not prevent direct API requests; the server must authorize every request against the session's tenant and role.",+ },+ {+ id: "controlled-client-same-origin-fetch",+ coveredByClientArtifactShield: false,+ authoritativeControlLocation: "server-side-application",+ explanation:+ "BLA runtime globals and AST shields execute inside the untrusted client context and carry no server identity or resource authorization authority.",+ },+ {+ id: "authorized-user-response-observation",+ coveredByClientArtifactShield: false,+ authoritativeControlLocation: "server-side-application",+ explanation:+ "BLA cannot prevent a user from recording network responses or data that their session is legitimately permitted to receive. Sensitive fields that the client does not strictly need must be omitted by the server before serialization (data minimization).",+ },+ ],+ };+}++// ============================================================================+// Self-Contained Local Reference Service & Client (Synthetic Multi-Tenant Fixture)+// ============================================================================++export type SyntheticRole = "viewer" | "admin";++export interface SyntheticSessionRecord {+ readonly sessionId: string;+ readonly userId: string;+ readonly tenantId: string;+ readonly role: SyntheticRole;+ readonly csrfToken: string;+ readonly expiresAtMs: number;+ revoked: boolean;+}++export interface InternalTenantDocumentRecord {+ readonly docId: string;+ readonly tenantId: string;+ title: string;+ quotaLimit: number;+ /** Sensitive backend-only field that must NEVER be serialized to client responses. */+ readonly internalSigningKeyMaterial: string;+ readonly internalBillingWebhookSecret: string;+}++export interface MinimizedClientDocumentDto {+ readonly docId: string;+ readonly tenantId: string;+ readonly title: string;+ readonly quotaLimit: number;+}++export interface SyntheticHttpRequest {+ readonly method: "GET" | "POST";+ readonly path: string;+ readonly origin: string;+ readonly sessionId?: string;+ readonly csrfToken?: string;+ readonly requestNonce?: string;+ readonly body?: Record<string, unknown>;+}++export interface SyntheticHttpResponse<T = unknown> {+ readonly status: number;+ readonly ok: boolean;+ readonly errorCode?:+ | "UNAUTHENTICATED"+ | "SESSION_EXPIRED_OR_REVOKED"+ | "CROSS_ORIGIN_REJECTED"+ | "CSRF_OR_REPLAY_REJECTED"+ | "FORBIDDEN_TENANT_OR_ROLE"+ | "NOT_FOUND";+ readonly data?: T;+}++/**+ * Small self-contained local reference service demonstrating authoritative server-side+ * session verification, tenant/object isolation, CSRF + replay protection, and+ * response data minimization (Issue #20).+ */+export class ReferenceTenantAuthorizationService {+ private readonly allowedOrigin: string;+ private readonly sessions = new Map<string, SyntheticSessionRecord>();+ private readonly documents = new Map<string, InternalTenantDocumentRecord>();+ private readonly consumedNonces = new Set<string>();+ private nowFn: () => number;++ constructor(options?: { allowedOrigin?: string; nowFn?: () => number }) {+ this.allowedOrigin = options?.allowedOrigin ?? "https://app.local.fixture";+ this.nowFn = options?.nowFn ?? (() => Date.now());+ }++ public issueSession(params: {+ readonly userId: string;+ readonly tenantId: string;+ readonly role: SyntheticRole;+ readonly ttlMs?: number;+ }): SyntheticSessionRecord {+ const sessionId = `sess_${randomBytes(12).toString("hex")}`;+ const csrfToken = `csrf_${randomBytes(12).toString("hex")}`;+ const record: SyntheticSessionRecord = {+ sessionId,+ userId: params.userId,+ tenantId: params.tenantId,+ role: params.role,+ csrfToken,+ expiresAtMs: this.nowFn() + (params.ttlMs ?? 60_000),+ revoked: false,+ };+ this.sessions.set(sessionId, record);+ return record;+ }++ public revokeSession(sessionId: string): boolean {+ const sess = this.sessions.get(sessionId);+ if (!sess) return false;+ sess.revoked = true;+ return true;+ }++ public seedDocument(doc: InternalTenantDocumentRecord): void {+ this.documents.set(doc.docId, { ...doc });+ }++ public snapshotDocumentState(docId: string): { title: string; quotaLimit: number } | undefined {+ const doc = this.documents.get(docId);+ if (!doc) return undefined;+ return { title: doc.title, quotaLimit: doc.quotaLimit };+ }++ private minimizeDocument(doc: InternalTenantDocumentRecord): MinimizedClientDocumentDto {+ // Data minimization: never include internalSigningKeyMaterial or internalBillingWebhookSecret+ return {+ docId: doc.docId,+ tenantId: doc.tenantId,+ title: doc.title,+ quotaLimit: doc.quotaLimit,+ };+ }++ public handleRequest(req: SyntheticHttpRequest): SyntheticHttpResponse {+ // 1. Validate session existence and active status on every request+ if (!req.sessionId) {+ return { status: 401, ok: false, errorCode: "UNAUTHENTICATED" };+ }+ const session = this.sessions.get(req.sessionId);+ if (!session || session.revoked || this.nowFn() >= session.expiresAtMs) {+ return { status: 401, ok: false, errorCode: "SESSION_EXPIRED_OR_REVOKED" };+ }++ // 2. Parse route `/api/tenants/:tenantId/documents/:docId`+ const match = /^\/api\/tenants\/([^/]+)\/documents\/([^/]+)$/.exec(req.path);+ if (!match) {+ return { status: 404, ok: false, errorCode: "NOT_FOUND" };+ }+ const [, requestedTenantId, requestedDocId] = match;++ // 3. Enforce tenant boundary before inspecting or mutating any object+ if (requestedTenantId !== session.tenantId) {+ return { status: 403, ok: false, errorCode: "FORBIDDEN_TENANT_OR_ROLE" };+ }++ const doc = this.documents.get(requestedDocId!);+ if (!doc || doc.tenantId !== session.tenantId) {+ return { status: 403, ok: false, errorCode: "FORBIDDEN_TENANT_OR_ROLE" };+ }++ if (req.method === "GET") {+ return {+ status: 200,+ ok: true,+ data: this.minimizeDocument(doc),+ };+ }++ // 4. State-changing request (POST): enforce origin, CSRF token, replay nonce, and role+ if (req.origin !== this.allowedOrigin) {+ return { status: 403, ok: false, errorCode: "CROSS_ORIGIN_REJECTED" };+ }+ if (+ !req.csrfToken ||+ req.csrfToken !== session.csrfToken ||+ !req.requestNonce ||+ req.requestNonce.trim().length < 8+ ) {+ return { status: 403, ok: false, errorCode: "CSRF_OR_REPLAY_REJECTED" };+ }+ const nonceKey = createHash("sha256")+ .update(`${session.sessionId}:${req.requestNonce}`)+ .digest("hex");+ if (this.consumedNonces.has(nonceKey)) {+ return { status: 403, ok: false, errorCode: "CSRF_OR_REPLAY_REJECTED" };+ }++ // Role check MUST happen before committing any state or consuming business state+ if (session.role !== "admin") {+ return { status: 403, ok: false, errorCode: "FORBIDDEN_TENANT_OR_ROLE" };+ }++ this.consumedNonces.add(nonceKey);++ if (typeof req.body?.title === "string" && req.body.title.trim().length > 0) {+ doc.title = req.body.title.trim();+ }+ if (typeof req.body?.quotaLimit === "number" && Number.isSafeInteger(req.body.quotaLimit)) {+ doc.quotaLimit = req.body.quotaLimit;+ }++ return {+ status: 200,+ ok: true,+ data: this.minimizeDocument(doc),+ };+ }+}diff --git a/src/core/debug-posture.ts b/src/core/debug-posture.tsnew file mode 100644index 0000000..223fe78--- /dev/null+++ b/src/core/debug-posture.ts@@ -0,0 +1,263 @@+import { existsSync, readFileSync, statSync } from "node:fs";+import { join, resolve } from "node:path";++export type DebugPostureStatus = "exposed" | "not-observed" | "unknown";++export interface DebugPostureCheck {+ readonly id:+ | "node-cli-inspector-exposure"+ | "chromium-remote-debugging-exposure"+ | "macos-entitlements-debug-posture"+ | "android-manifest-debuggable-posture";+ readonly platform: "cross-platform" | "macos" | "android";+ readonly status: DebugPostureStatus;+ readonly observedConfig: string;+ readonly restrictedChannel: string;+ readonly remediation: string;+}++export interface ProductionDebugPostureReport {+ readonly targetPath: string;+ readonly overallPosture: "exposed" | "not-observed" | "unknown";+ readonly checks: readonly DebugPostureCheck[];+ readonly runtimeBoundaryContract: {+ readonly shadowObjectsClassification: "decorative-deception-signal";+ readonly absenceOfRuntimeMarkersImpliesNoDebugger: false;+ readonly blocksFridaOrGdbWithLocalPrivileges: false;+ readonly blocksRuntimeStateRecovery: false;+ readonly secretStorageGuidance: string;+ };+}++export interface InspectDebugPostureOptions {+ readonly targetDir: string;+ readonly packageJsonPath?: string;+ readonly envFilePath?: string;+ readonly macosEntitlementsPath?: string;+ readonly androidManifestPath?: string;+}++/**+ * Read-only production debug exposure inspector (Issue #19).+ *+ * Inspects authorized local build/deployment configuration files to identify+ * unnecessary debug/inspector entry points (`--inspect`, `--remote-debugging-port`,+ * `com.apple.security.get-task-allow`, `android:debuggable="true"`).+ *+ * Never probes network ports, never attaches to processes, and never claims that+ * client-side JS markers can block Frida/GDB/CDP when the observer holds OS privileges.+ */+export function inspectProductionDebugPosture(+ options: InspectDebugPostureOptions,+): ProductionDebugPostureReport {+ const rootDir = resolve(options.targetDir);+ const pkgPath = options.packageJsonPath+ ? resolve(options.packageJsonPath)+ : join(rootDir, "package.json");+ const envPath = options.envFilePath+ ? resolve(options.envFilePath)+ : join(rootDir, ".env.production");+ const entitlementsPath = options.macosEntitlementsPath+ ? resolve(options.macosEntitlementsPath)+ : join(rootDir, "entitlements.plist");+ const androidManifestPath = options.androidManifestPath+ ? resolve(options.androidManifestPath)+ : join(rootDir, "AndroidManifest.xml");++ const checks: DebugPostureCheck[] = [];++ // 1. Node CLI inspector & NODE_OPTIONS check+ {+ const sources: string[] = [];+ const exposedFlags: string[] = [];++ if (existsSync(pkgPath) && statSync(pkgPath).isFile()) {+ try {+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as {+ scripts?: Record<string, string>;+ };+ if (pkg.scripts && typeof pkg.scripts === "object") {+ for (const [name, cmd] of Object.entries(pkg.scripts)) {+ if (typeof cmd !== "string") continue;+ // Focus on production/start/serve/pack scripts or all scripts+ if (/(^|[\s"'])(--inspect(?:-brk|-port)?|ELECTRON_RUN_AS_NODE=1)\b/.test(cmd)) {+ exposedFlags.push(`package.json#scripts.${name}: "${cmd}"`);+ }+ }+ sources.push("package.json#scripts");+ }+ } catch {+ // Ignore malformed package.json here; status falls back if no valid sources+ }+ }++ if (existsSync(envPath) && statSync(envPath).isFile()) {+ const envText = readFileSync(envPath, "utf8");+ sources.push(".env.production");+ if (/(--inspect(?:-brk|-port)?|ELECTRON_RUN_AS_NODE\s*=\s*1)/.test(envText)) {+ exposedFlags.push(`.env.production contains inspector/run-as-node directive`);+ }+ }++ const status: DebugPostureStatus =+ exposedFlags.length > 0+ ? "exposed"+ : sources.length > 0+ ? "not-observed"+ : "unknown";++ checks.push({+ id: "node-cli-inspector-exposure",+ platform: "cross-platform",+ status,+ observedConfig:+ exposedFlags.length > 0+ ? exposedFlags.join("; ")+ : sources.length > 0+ ? `Inspected ${sources.join(", ")}; no --inspect or ELECTRON_RUN_AS_NODE flags found.`+ : "No package.json or .env.production found to verify Node launch flags.",+ restrictedChannel: "Node.js V8 Inspector WebSocket (--inspect / NODE_OPTIONS)",+ remediation:+ "Remove --inspect, --inspect-brk, and ELECTRON_RUN_AS_NODE=1 from production start scripts and environment files, and disable RunAsNode / EnableNodeCliInspectArguments in Electron fuses.",+ });+ }++ // 2. Chromium / WebView remote debugging port exposure+ {+ const sources: string[] = [];+ const exposedFlags: string[] = [];++ if (existsSync(pkgPath) && statSync(pkgPath).isFile()) {+ try {+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as {+ scripts?: Record<string, string>;+ };+ if (pkg.scripts && typeof pkg.scripts === "object") {+ for (const [name, cmd] of Object.entries(pkg.scripts)) {+ if (typeof cmd !== "string") continue;+ if (/--remote-debugging-(?:port|pipe|address)|--remote-allow-origins/.test(cmd)) {+ exposedFlags.push(`package.json#scripts.${name}: "${cmd}"`);+ }+ }+ sources.push("package.json#scripts");+ }+ } catch {+ // Ignore+ }+ }++ const status: DebugPostureStatus =+ exposedFlags.length > 0+ ? "exposed"+ : sources.length > 0+ ? "not-observed"+ : "unknown";++ checks.push({+ id: "chromium-remote-debugging-exposure",+ platform: "cross-platform",+ status,+ observedConfig:+ exposedFlags.length > 0+ ? exposedFlags.join("; ")+ : sources.length > 0+ ? `Inspected ${sources.join(", ")}; no --remote-debugging-port flags found.`+ : "No launch configuration found to verify Chromium remote debugging flags.",+ restrictedChannel: "Chrome DevTools Protocol (CDP) HTTP/WebSocket endpoint",+ remediation:+ "Remove --remote-debugging-port and --remote-allow-origins from production launch scripts and BrowserWindow startup switches.",+ });+ }++ // 3. macOS Entitlements / Hardened Runtime debug posture+ {+ if (existsSync(entitlementsPath) && statSync(entitlementsPath).isFile()) {+ const xml = readFileSync(entitlementsPath, "utf8");+ const riskyKeys = [+ "com.apple.security.get-task-allow",+ "com.apple.security.cs.allow-dyld-environment-variables",+ "com.apple.security.cs.disable-library-validation",+ "com.apple.security.cs.allow-unsigned-executable-memory",+ ];+ const enabledKeys = riskyKeys.filter((key) => {+ const regex = new RegExp(+ `<key>\\s*${key.replace(/\./g, "\\.")}\\s*</key>\\s*<true\\s*/>`,+ "i",+ );+ return regex.test(xml);+ });++ checks.push({+ id: "macos-entitlements-debug-posture",+ platform: "macos",+ status: enabledKeys.length > 0 ? "exposed" : "not-observed",+ observedConfig:+ enabledKeys.length > 0+ ? `Enabled debug/injection entitlements in ${entitlementsPath}: ${enabledKeys.join(", ")}`+ : `Inspected ${entitlementsPath}; get-task-allow and dyld injection entitlements are not enabled.`,+ restrictedChannel: "macOS task_for_pid / LLDB / Frida attach & DYLD_INSERT_LIBRARIES",+ remediation:+ "Set com.apple.security.get-task-allow, allow-dyld-environment-variables, and disable-library-validation to false (or remove them) in production release entitlements with Hardened Runtime enabled.",+ });+ } else {+ checks.push({+ id: "macos-entitlements-debug-posture",+ platform: "macos",+ status: "unknown",+ observedConfig: "No macOS entitlements.plist provided or discovered in target directory.",+ restrictedChannel: "macOS task_for_pid / LLDB / Frida attach & DYLD_INSERT_LIBRARIES",+ remediation:+ "Provide macosEntitlementsPath to verify that com.apple.security.get-task-allow is omitted in release builds.",+ });+ }+ }++ // 4. Android Manifest debuggable posture+ {+ if (existsSync(androidManifestPath) && statSync(androidManifestPath).isFile()) {+ const xml = readFileSync(androidManifestPath, "utf8");+ const isDebuggable = /android:debuggable\s*=\s*["']true["']/i.test(xml);+ checks.push({+ id: "android-manifest-debuggable-posture",+ platform: "android",+ status: isDebuggable ? "exposed" : "not-observed",+ observedConfig: isDebuggable+ ? `android:debuggable="true" observed in ${androidManifestPath}`+ : `Inspected ${androidManifestPath}; android:debuggable="true" is not set.`,+ restrictedChannel: "Android JDWP / run-as / Frida gadget attach on non-rooted devices",+ remediation:+ "Ensure android:debuggable=\"false\" in release buildTypes in build.gradle / AndroidManifest.xml.",+ });+ } else {+ checks.push({+ id: "android-manifest-debuggable-posture",+ platform: "android",+ status: "unknown",+ observedConfig: "No AndroidManifest.xml provided or discovered in target directory.",+ restrictedChannel: "Android JDWP / run-as / Frida gadget attach on non-rooted devices",+ remediation:+ "Provide androidManifestPath to verify that android:debuggable is false in release builds.",+ });+ }+ }++ const overallPosture: DebugPostureStatus = checks.some((c) => c.status === "exposed")+ ? "exposed"+ : checks.some((c) => c.status === "not-observed")+ ? "not-observed"+ : "unknown";++ return {+ targetPath: rootDir,+ overallPosture,+ checks,+ runtimeBoundaryContract: {+ shadowObjectsClassification: "decorative-deception-signal",+ absenceOfRuntimeMarkersImpliesNoDebugger: false,+ blocksFridaOrGdbWithLocalPrivileges: false,+ blocksRuntimeStateRecovery: false,+ secretStorageGuidance:+ "BLA JavaScript runtime shields cannot guarantee confidentiality of plaintext or decryption keys held by a client process when the observer has OS-level debugging/instrumentation permissions (e.g., Frida, GDB, LLDB, or root/admin access). Keep authoritative access control and long-lived secrets in trusted server or hardware boundaries.",+ },+ };+}diff --git a/src/engine/protector.ts b/src/engine/protector.tsindex 2723643..3fc9ed1 100644--- a/src/engine/protector.ts+++ b/src/engine/protector.ts@@ -19,12 +19,12 @@ import type {import { generateChaffPayloads } from "../shields/chaff/chaff-generator.js";import { transformJavaScriptWithBlaShield } from "../shields/javascript/ast-shield.js";import { generateHoneySourceMap } from "../shields/formats/sourcemap.js";-import { packAsarBuffer, unpackAsarBuffer, type VirtualAsarFile } from "../shields/formats/asar.js";+import { packAsarBuffer, unpackAsarBuffer, validateAsarProtectionInput, type VirtualAsarFile } from "../shields/formats/asar.js";import { protectWasmBinary } from "../shields/formats/wasm.js";-import { protectPythonPycBuffer, protectPythonSource } from "../shields/formats/python.js";-import { protectNativeBinary } from "../shields/formats/native.js";+import { findPythonPrologueInsertionOffset, protectPythonPycBuffer, protectPythonSource } from "../shields/formats/python.js";+import { protectNativeBinary, validateElf64Layout } from "../shields/formats/native.js";import { protectZipOrApkBuffer, validateZipProtectionInput, UnsupportedApkProtectionError } from "../shields/formats/archive.js";-import { protectSqliteBuffer } from "../shields/formats/sqlite.js";+import { protectSqliteBuffer, validateSqliteFileInput } from "../shields/formats/sqlite.js";import { protectGgufBuffer, protectSafetensorsBuffer } from "../shields/formats/model.js";import { protectAndroidDexBuffer, protectIl2cppMetadataBuffer } from "../shields/formats/mobile-game.js";import { protectApplePlistBuffer } from "../shields/formats/apple-plist.js";@@ -60,6 +60,10 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {);assertSafeOutputPath(absInput, absOutput, format === "directory", options.inPlace);if (format === "archive-zip") validateZipProtectionInput(readFileSync(absInput));+ if (format === "electron-asar") validateAsarProtectionInput(readFileSync(absInput));+ if (format === "sqlite") validateSqliteFileInput(absInput);+ if (format === "python-source") findPythonPrologueInsertionOffset(readFileSync(absInput, "utf8"));+ if (format === "native-elf") validateElf64Layout(readFileSync(absInput));const intensity = options.intensity ?? "balanced";const seed = String(options.seed ?? "bla-shield-seed-v1");diff --git a/src/index.ts b/src/index.tsindex e9bf735..e0f282e 100644--- a/src/index.ts+++ b/src/index.ts@@ -14,29 +14,54 @@ export {} from "./shields/runtime/runtime-shield.js";export {transformJavaScriptWithBlaShield,+ InvalidJavaScriptCarrierError,+ inferJsLoaderFromPath,+ inferJsCarrierFromPath,+ collectEsmExportedSymbols,+ type JsCarrierType,+ type JsLoaderType,+ type JsTransformOptions,type JsShieldTransformResult,} from "./shields/javascript/ast-shield.js";export { generateHoneySourceMap, type HoneySourceMap } from "./shields/formats/sourcemap.js";export {+ UnsupportedAsarError,+ validateAsarBuffer,+ validateAsarProtectionInput,unpackAsarBuffer,packAsarBuffer,type VirtualAsarFile,+ type AsarHeaderNode,+ type AsarValidationOptions,} from "./shields/formats/asar.js";export {+ UnsupportedElectronFuseContextError,+ inspectElectronFusesBuffer,inspectElectronFusesInBuffer,+ hardenElectronFusesWithContext,hardenAndOverflowElectronFuses,+ type ElectronFuseStatus,+ type ElectronFuseInspectionResult,type ElectronFuseInspectionSummary,+ type ElectronHardeningContext,+ type ElectronHardeningReport,} from "./shields/formats/electron-fuses.js";export { inspectWasmBinary, protectWasmBinary } from "./shields/formats/wasm.js";export {+ InvalidPythonSourceError,+ findPythonPrologueInsertionOffset,protectPythonSource,inspectPythonPyc,protectPythonPycBuffer,+ type PythonPrologueAnalysis,} from "./shields/formats/python.js";export {+ InvalidNativeBinaryError,+ validateElf64Layout,inspectNativeBinary,protectNativeBinary,buildDecoyRustAuditablePayload,+ type Elf64LayoutSummary,} from "./shields/formats/native.js";export {emitCompileTimeNativeHeader,@@ -44,10 +69,20 @@ export {type EmittedNativeHeader,} from "./shields/formats/headers.js";export {+ SqliteWalConsistencyError,+ DEFAULT_SQLITE_SENSITIVITY_POLICY,+ validateSqliteFileInput,+ validateSqliteStandaloneBuffer,+ evaluateSqliteSensitivityPolicy,+ minimizeSqliteDatabaseBuffer,inspectSqliteBuffer,protectSqliteBuffer,buildSampleSqliteDatabase,type SqliteInspectionSummary,+ type SqliteSensitivityRule,+ type SqliteSensitivityPolicy,+ type SqliteSensitiveColumnFinding,+ type SqlitePolicyEvaluationReport,} from "./shields/formats/sqlite.js";export {buildSafetensorsBuffer,@@ -94,8 +129,13 @@ export * from "./shields/formats/dotnet-managed.js";export * from "./shields/formats/jvm-bytecode.js";export * from "./core/config.js";export * from "./core/sarif.js";+export * from "./core/release-plan.js";+export * from "./core/debug-posture.js";+export * from "./core/coverage-contract.js";export {resolveSupportedAgentClients,+ detectInstalledClients,+ CLIENT_COMPATIBILITY_MATRIX,type SupportedAgentClientId,} from "./setup/clients.js";export { runSetup, runUninstall } from "./setup/setup.js";diff --git a/src/shields/formats/sqlite.ts b/src/shields/formats/sqlite.tsindex 8a30f7a..d14a8c7 100644--- a/src/shields/formats/sqlite.ts+++ b/src/shields/formats/sqlite.ts@@ -1,33 +1,399 @@-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createHash } from "node:crypto";+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { join, resolve } from "node:path";import { SeededPrng } from "../../core/prng.js";import { getDatabaseSyncClass } from "../../core/sqlite-runtime.js";import type { ProtectionIntensity } from "../../core/types.js";import { generateChaffPayloads } from "../chaff/chaff-generator.js";+/**+ * Thrown when a SQLite database input cannot be proven complete or consistent+ * (e.g., active/uncheckpointed WAL mode, companion -wal/-shm/-journal files,+ * truncated header, or failed PRAGMA integrity_check).+ */+export class SqliteWalConsistencyError extends Error {+ constructor(reason: string) {+ super(`SQLite consistency admission failed: ${reason}`);+ this.name = "SqliteWalConsistencyError";+ }+}++export interface SqliteSensitivityRule {+ readonly ruleId: string;+ readonly tablePattern: string | RegExp;+ readonly columnPattern: string | RegExp;+ readonly classification: "forbidden-in-client-artifact" | "short-lived-scoped-only";+ readonly remediation: string;+}++export interface SqliteSensitivityPolicy {+ readonly policyId: string;+ readonly rules: readonly SqliteSensitivityRule[];+}++export interface SqliteSensitiveColumnFinding {+ readonly ruleId: string;+ readonly table: string;+ readonly column: string;+ readonly nonNullRowCount: number;+ readonly classification: "forbidden-in-client-artifact" | "short-lived-scoped-only";+ readonly status: "exposed";+ readonly remediation: string;+}++export interface SqlitePolicyEvaluationReport {+ readonly validSqlite: boolean;+ readonly formatStatus: "sqlite3-plaintext" | "unsupported-or-encrypted";+ readonly decorationState: "decorated" | "undecorated" | "unsupported-or-encrypted";+ readonly businessDataState: "business-data-preserved" | "empty" | "unknown";+ readonly confidentialityState:+ | "confidentiality-not-established"+ | "policy-violation-exposed"+ | "policy-compliant-minimized"+ | "unsupported-or-encrypted";+ readonly businessTables: readonly string[];+ readonly honeyTablesCount: number;+ readonly findings: readonly SqliteSensitiveColumnFinding[];+ readonly residualRiskNotice: string;+}+export interface SqliteInspectionSummary {readonly validSqlite: boolean;readonly tableNames: readonly string[];+ readonly businessTables: readonly string[];readonly honeyTablesCount: number;readonly hasGeneratedTrapColumns: boolean;readonly blaProtected: boolean;+ readonly decorationState: "decorated" | "undecorated" | "unsupported-or-encrypted";+ readonly businessDataState: "business-data-preserved" | "empty" | "unknown";+ readonly confidentialityState:+ | "confidentiality-not-established"+ | "policy-violation-exposed"+ | "policy-compliant-minimized"+ | "unsupported-or-encrypted";+ readonly policyFindings: readonly SqliteSensitiveColumnFinding[];+}++export const DEFAULT_SQLITE_SENSITIVITY_POLICY: SqliteSensitivityPolicy = {+ policyId: "bla-default-sqlite-data-minimization-v1",+ rules: [+ {+ ruleId: "SQLITE-SEC-001",+ tablePattern: /.*/i,+ columnPattern: /^(offline_token|refresh_token|access_token|session_secret|private_key|master_key|secret_key|api_key|password_hash|client_secret)$/i,+ classification: "forbidden-in-client-artifact",+ remediation:+ "Do not distribute long-lived tokens or secret keys in client SQLite caches. Use short-lived server-revocable leases or OS-keystore-backed encryption without shipping hardcoded keys in the same bundle.",+ },+ ],+};++function matchesPattern(value: string, pattern: string | RegExp): boolean {+ if (typeof pattern === "string") {+ if (pattern === "*") return true;+ return value.toLowerCase() === pattern.toLowerCase();+ }+ return pattern.test(value);+}++function quoteIdentifier(id: string): string {+ return `"${id.replace(/"/g, '""')}"`;+}++function isHoneyTableName(name: string): boolean {+ return name.startsWith("_bla_") || name.includes("enclave_");+}++function hasValidSqlite3Header(bytes: Buffer): boolean {+ return (+ bytes.length >= 100 &&+ bytes.subarray(0, 16).toString("latin1") === "SQLite format 3\0"+ );}/**- * Inspects a SQLite 3 database file or buffer using `node:sqlite`.+ * Checks whether a SQLite header indicates WAL mode (file format write version = 2+ * at offset 18 or read version = 2 at offset 19).+ */+export function isSqliteHeaderWalMode(bytes: Buffer): boolean {+ if (!hasValidSqlite3Header(bytes)) return false;+ return bytes[18] === 2 || bytes[19] === 2;+}++/**+ * Validates that a on-disk SQLite file path is a standalone, quiescent database+ * with no uncheckpointed WAL (`-wal`), shared-memory (`-shm`), or hot rollback+ * journal (`-journal`) companion files before protection runs.+ */+export function validateSqliteFileInput(dbPath: string): Buffer {+ const absPath = resolve(dbPath);+ if (!existsSync(absPath)) {+ throw new SqliteWalConsistencyError(`Database file does not exist: ${absPath}`);+ }+ const walPath = `${absPath}-wal`;+ const shmPath = `${absPath}-shm`;+ const journalPath = `${absPath}-journal`;++ if (existsSync(journalPath)) {+ const journalSize = statSync(journalPath).size;+ throw new SqliteWalConsistencyError(+ `Hot rollback journal detected (${journalPath}, ${journalSize} bytes). Export a consistent standalone backup before running protection.`,+ );+ }++ if (existsSync(walPath) || existsSync(shmPath)) {+ const walSize = existsSync(walPath) ? statSync(walPath).size : 0;+ throw new SqliteWalConsistencyError(+ `Companion WAL/SHM files detected (${walPath}, ${walSize} bytes). Active or uncheckpointed WAL data would be lost if only the main DB file were rewritten. Run a clean checkpoint/backup (e.g. VACUUM INTO) first.`,+ );+ }++ const bytes = readFileSync(absPath);+ validateSqliteStandaloneBuffer(bytes);+ return bytes;+}++/**+ * Validates that a single SQLite buffer is a valid, self-contained SQLite 3+ * snapshot (not in WAL mode requiring external `-wal` state) and passes `PRAGMA integrity_check`.*/-export function inspectSqliteBuffer(bytes: Buffer): SqliteInspectionSummary {+export function validateSqliteStandaloneBuffer(bytes: Buffer): void {+ if (!hasValidSqlite3Header(bytes)) {+ throw new SqliteWalConsistencyError(+ "Input is not a valid SQLite 3 database header (minimum 100 bytes with 'SQLite format 3\\0' magic).",+ );+ }+ const pageSizeRaw = bytes.readUInt16BE(16);+ const pageSize = pageSizeRaw === 1 ? 65536 : pageSizeRaw;if (- bytes.length < 100 ||- bytes.subarray(0, 16).toString("latin1") !== "SQLite format 3\0"+ pageSize < 512 ||+ pageSize > 65536 ||+ (pageSize & (pageSize - 1)) !== 0 ||+ bytes.length % pageSize !== 0) {+ throw new SqliteWalConsistencyError(+ `SQLite file size (${bytes.length}) is not an exact multiple of valid page size (${pageSize}); database appears truncated.`,+ );+ }+ if (isSqliteHeaderWalMode(bytes)) {+ throw new SqliteWalConsistencyError(+ "SQLite header indicates WAL mode (format write/read version 2 at bytes 18..19). A single buffer cannot guarantee that committed WAL frames are included. Export a standalone DELETE-mode backup (e.g. VACUUM INTO or PRAGMA journal_mode=DELETE) before protection.",+ );+ }++ const DatabaseSync = getDatabaseSyncClass();+ const tempDir = mkdtempSync(join(tmpdir(), "bla-sqlite-validate-"));+ const dbPath = join(tempDir, "validate.sqlite");+ try {+ writeFileSync(dbPath, bytes);+ const db = new DatabaseSync(dbPath, { readOnly: true });+ try {+ db.function("bla_enclave_unseal", { deterministic: true }, (blob: unknown) =>+ `ENCLAVE_SEALED:${String(blob ?? "")}`,+ );+ const integrity = db.prepare("PRAGMA integrity_check").all() as Array<{+ integrity_check?: string;+ }>;+ if (integrity.length !== 1 || integrity[0]?.integrity_check !== "ok") {+ throw new SqliteWalConsistencyError("SQLite PRAGMA integrity_check failed.");+ }+ // Also ensure sqlite_schema is readable+ db.prepare("SELECT count(*) FROM sqlite_schema").get();+ } finally {+ db.close();+ }+ } catch (err) {+ if (err instanceof SqliteWalConsistencyError) throw err;+ throw new SqliteWalConsistencyError(+ `SQLite database failed read/integrity validation: ${err instanceof Error ? err.message : String(err)}`,+ );+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+}++interface BusinessTableDigest {+ readonly name: string;+ readonly rowCount: number;+ readonly rowsSha256: string;+}++function snapshotBusinessTables(+ db: InstanceType<ReturnType<typeof getDatabaseSyncClass>>,+): readonly BusinessTableDigest[] {+ const tables = db+ .prepare(+ "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",+ )+ .all() as Array<{ name: string }>;++ const digests: BusinessTableDigest[] = [];+ for (const { name } of tables) {+ if (isHoneyTableName(name)) continue;+ const rows = db+ .prepare(`SELECT * FROM ${quoteIdentifier(name)} ORDER BY rowid`)+ .all();+ const hash = createHash("sha256")+ .update(JSON.stringify(rows))+ .digest("hex");+ digests.push({+ name,+ rowCount: rows.length,+ rowsSha256: hash,+ });+ }+ return digests;+}++/**+ * Evaluates a SQLite buffer against an explicit sensitive-column policy without+ * ever emitting or logging raw secret values. Distinguishes honey-table decoration+ * from actual data confidentiality.+ */+export function evaluateSqliteSensitivityPolicy(+ bytes: Buffer,+ policy: SqliteSensitivityPolicy = DEFAULT_SQLITE_SENSITIVITY_POLICY,+): SqlitePolicyEvaluationReport {+ const residualRiskNotice =+ "Honey tables and generated-column traps only increase static/automated inspection friction; they do not encrypt business tables. Any plaintext or client-decryptable data shipped in an offline database remains readable by a local principal with sufficient process or file permissions.";++ if (!hasValidSqlite3Header(bytes)) {+ return {+ validSqlite: false,+ formatStatus: "unsupported-or-encrypted",+ decorationState: "unsupported-or-encrypted",+ businessDataState: "unknown",+ confidentialityState: "unsupported-or-encrypted",+ businessTables: [],+ honeyTablesCount: 0,+ findings: [],+ residualRiskNotice,+ };+ }++ const DatabaseSync = getDatabaseSyncClass();+ const tempDir = mkdtempSync(join(tmpdir(), "bla-sqlite-policy-"));+ const dbPath = join(tempDir, "policy.sqlite");+ try {+ writeFileSync(dbPath, bytes);+ const db = new DatabaseSync(dbPath, { readOnly: true });+ try {+ const rows = db+ .prepare(+ "SELECT name, sql FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",+ )+ .all() as Array<{ name: string; sql: string | null }>;++ const tableNames = rows.map((r) => r.name);+ const honeyTablesCount = tableNames.filter(isHoneyTableName).length;+ const businessTables = tableNames.filter((n) => !isHoneyTableName(n));+ const hasGeneratedTrapColumns = rows.some(+ (r) => typeof r.sql === "string" && r.sql.includes("GENERATED ALWAYS AS"),+ );+ const decorated = honeyTablesCount > 0 || hasGeneratedTrapColumns;++ let totalBusinessRows = 0;+ const findings: SqliteSensitiveColumnFinding[] = [];++ for (const table of businessTables) {+ const countRow = db+ .prepare(`SELECT COUNT(*) AS cnt FROM ${quoteIdentifier(table)}`)+ .get() as { cnt: number } | undefined;+ const tableRows = Number(countRow?.cnt ?? 0);+ totalBusinessRows += tableRows;++ const columns = db+ .prepare(`PRAGMA table_info(${quoteIdentifier(table)})`)+ .all() as Array<{ name: string; type: string }>;++ for (const col of columns) {+ for (const rule of policy.rules) {+ if (+ matchesPattern(table, rule.tablePattern) &&+ matchesPattern(col.name, rule.columnPattern)+ ) {+ const nonNullRow = db+ .prepare(+ `SELECT COUNT(*) AS cnt FROM ${quoteIdentifier(table)} WHERE ${quoteIdentifier(col.name)} IS NOT NULL AND CAST(${quoteIdentifier(col.name)} AS TEXT) != ''`,+ )+ .get() as { cnt: number } | undefined;+ const nonNullRowCount = Number(nonNullRow?.cnt ?? 0);+ if (nonNullRowCount > 0) {+ findings.push({+ ruleId: rule.ruleId,+ table,+ column: col.name,+ nonNullRowCount,+ classification: rule.classification,+ status: "exposed",+ remediation: rule.remediation,+ });+ }+ }+ }+ }+ }++ const businessDataState =+ totalBusinessRows > 0 ? "business-data-preserved" : "empty";+ const confidentialityState =+ findings.length > 0+ ? "policy-violation-exposed"+ : policy.rules.length > 0 && businessTables.length > 0+ ? "confidentiality-not-established"+ : "confidentiality-not-established";++ return {+ validSqlite: true,+ formatStatus: "sqlite3-plaintext",+ decorationState: decorated ? "decorated" : "undecorated",+ businessDataState,+ confidentialityState,+ businessTables,+ honeyTablesCount,+ findings,+ residualRiskNotice,+ };+ } finally {+ db.close();+ }+ } catch {+ return {+ validSqlite: false,+ formatStatus: "unsupported-or-encrypted",+ decorationState: "unsupported-or-encrypted",+ businessDataState: "unknown",+ confidentialityState: "unsupported-or-encrypted",+ businessTables: [],+ honeyTablesCount: 0,+ findings: [],+ residualRiskNotice,+ };+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+}++/**+ * Inspects a SQLite 3 database file or buffer using `node:sqlite`.+ */+export function inspectSqliteBuffer(+ bytes: Buffer,+ policy: SqliteSensitivityPolicy = DEFAULT_SQLITE_SENSITIVITY_POLICY,+): SqliteInspectionSummary {+ if (!hasValidSqlite3Header(bytes)) {return {validSqlite: false,tableNames: [],+ businessTables: [],honeyTablesCount: 0,hasGeneratedTrapColumns: false,blaProtected: false,+ decorationState: "unsupported-or-encrypted",+ businessDataState: "unknown",+ confidentialityState: "unsupported-or-encrypted",+ policyFindings: [],};}@@ -45,20 +411,25 @@ export function inspectSqliteBuffer(bytes: Buffer): SqliteInspectionSummary {.all() as Array<{ name: string; sql: string | null }>;const tableNames = rows.map((r) => r.name);- const honeyTablesCount = tableNames.filter(- (n) => n.startsWith("_bla_") || n.includes("enclave_"),- ).length;+ const honeyTablesCount = tableNames.filter(isHoneyTableName).length;+ const businessTables = tableNames.filter((n) => !isHoneyTableName(n));const hasGeneratedTrapColumns = rows.some((r) => typeof r.sql === "string" && r.sql.includes("GENERATED ALWAYS AS"),);const blaProtected = honeyTablesCount > 0 || hasGeneratedTrapColumns;+ const policyEval = evaluateSqliteSensitivityPolicy(bytes, policy);return {validSqlite: true,tableNames,+ businessTables,honeyTablesCount,hasGeneratedTrapColumns,blaProtected,+ decorationState: blaProtected ? "decorated" : "undecorated",+ businessDataState: policyEval.businessDataState,+ confidentialityState: policyEval.confidentialityState,+ policyFindings: policyEval.findings,};} finally {db.close();@@ -67,9 +438,14 @@ export function inspectSqliteBuffer(bytes: Buffer): SqliteInspectionSummary {return {validSqlite: false,tableNames: [],+ businessTables: [],honeyTablesCount: 0,hasGeneratedTrapColumns: false,blaProtected: false,+ decorationState: "unsupported-or-encrypted",+ businessDataState: "unknown",+ confidentialityState: "unsupported-or-encrypted",+ policyFindings: [],};} finally {rmSync(tempDir, { recursive: true, force: true });@@ -77,21 +453,44 @@ export function inspectSqliteBuffer(bytes: Buffer): SqliteInspectionSummary {}/**- * Protects a SQLite 3 database file (`.sqlite`, `.db`, `.sqlite3`) against- * REA's `inspect-sqlite-database` (`src/sqlite/SqliteDatabaseInspection.ts`):+ * Data minimization helper: removes or redacts specified sensitive columns from a+ * standalone SQLite database snapshot so forbidden secrets are never shipped in client artifacts.+ */+export function minimizeSqliteDatabaseBuffer(+ bytes: Buffer,+ columnsToDrop: readonly { readonly table: string; readonly column: string }[],+): Buffer {+ validateSqliteStandaloneBuffer(bytes);+ const DatabaseSync = getDatabaseSyncClass();+ const tempDir = mkdtempSync(join(tmpdir(), "bla-sqlite-minimize-"));+ const dbPath = join(tempDir, "minimize.sqlite");+ try {+ writeFileSync(dbPath, bytes);+ const db = new DatabaseSync(dbPath);+ try {+ for (const { table, column } of columnsToDrop) {+ db.exec(+ `ALTER TABLE ${quoteIdentifier(table)} DROP COLUMN ${quoteIdentifier(column)}`,+ );+ }+ db.exec("VACUUM");+ } finally {+ db.close();+ }+ return readFileSync(dbPath);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+}++/**+ * Protects a standalone, checkpointed SQLite 3 database buffer by injecting decoy+ * enclave honey tables and virtual generated-column traps while preserving 100% of+ * existing business tables and rows.*- * 1. **Honey Tables & Enclave Ledger Rows**: Injects realistic enterprise TEE/SGX- * tables (`_bla_enclave_key_hierarchy`, `_bla_tpm2_attestation_ledger`,- * `_bla_zero_trust_session_leases`) populated with decoy cryptographic manifests.- * 2. **Generated Column Expression Trap (`SqliteColumnEvaluationFailure`)**:- * Adds `GENERATED ALWAYS AS (bla_enclave_unseal(sealed_payload)) VIRTUAL` columns- * to honey tables (and optionally adds a virtual enclave audit column to existing tables).- * When REA opens the snapshot on its bare `readOnly: true, allowExtension: false`- * connection (`SqliteDatabaseInspection.ts:792`) without the `bla_enclave_unseal`- * application scalar function registered, REA's `SELECT` projection hits- * `SqliteColumnEvaluationFailure` (`SQLite cannot evaluate selected column(s) ... on REA's read-only connection`)!- * 3. **Schema Inventory Chaff**: Adds decoy views and triggers referencing hardware- * enclave state so `rea inspect-sqlite-database` harvests decoy schema topology.+ * NOTE: This decorates the database against automated schema/row harvesting; it does+ * NOT encrypt business columns (`confidentialityState: "confidentiality-not-established"`).+ * Fails closed (`SqliteWalConsistencyError`) if the input is in WAL mode, truncated, or corrupt.*/export function protectSqliteBuffer(bytes: Buffer,@@ -104,7 +503,12 @@ export function protectSqliteBuffer(readonly honeyTablesInjected: number;readonly generatedTrapColumnsAdded: number;readonly chaffPayloadsEmbedded: number;+ readonly decorationState: "decorated";+ readonly businessDataState: "business-data-preserved" | "empty";+ readonly confidentialityState: "confidentiality-not-established" | "policy-violation-exposed";} {+ validateSqliteStandaloneBuffer(bytes);+const DatabaseSync = getDatabaseSyncClass();const intensity = options.intensity ?? "balanced";const prng = new SeededPrng(options.seed ?? "bla-sqlite-shield-v1");@@ -114,22 +518,16 @@ export function protectSqliteBuffer(const dbPath = join(tempDir, "target.sqlite");try {- if (- bytes.length >= 100 &&- bytes.subarray(0, 16).toString("latin1") === "SQLite format 3\0"- ) {- writeFileSync(dbPath, bytes);- } else {- // Initialize a fresh SQLite database if buffer was empty- const initDb = new DatabaseSync(dbPath);- initDb.close();- }+ writeFileSync(dbPath, bytes);const db = new DatabaseSync(dbPath);let honeyTablesInjected = 0;let generatedTrapColumnsAdded = 0;+ let beforeDigests: readonly BusinessTableDigest[] = [];try {+ beforeDigests = snapshotBusinessTables(db);+// Register the scalar function during protection so INSERT/DDL validation succeeds cleanlydb.function("bla_enclave_unseal", { deterministic: true }, (blob: unknown) =>`ENCLAVE_SEALED:${String(blob ?? "")}`,@@ -205,16 +603,32 @@ export function protectSqliteBuffer(1924905600 + i * 3600,);}++ const afterDigests = snapshotBusinessTables(db);+ if (JSON.stringify(beforeDigests) !== JSON.stringify(afterDigests)) {+ throw new SqliteWalConsistencyError(+ "Post-transform business table digest mismatch; aborting output.",+ );+ }} finally {db.close();}const outBuffer = readFileSync(dbPath);+ validateSqliteStandaloneBuffer(outBuffer);+ const policyEval = evaluateSqliteSensitivityPolicy(outBuffer);+return {buffer: outBuffer,honeyTablesInjected,generatedTrapColumnsAdded,chaffPayloadsEmbedded: chaffPayloads.length,+ decorationState: "decorated",+ businessDataState: policyEval.businessDataState === "business-data-preserved" ? "business-data-preserved" : "empty",+ confidentialityState:+ policyEval.confidentialityState === "policy-violation-exposed"+ ? "policy-violation-exposed"+ : "confidentiality-not-established",};} finally {rmSync(tempDir, { recursive: true, force: true });diff --git a/src/shields/runtime/runtime-shield.ts b/src/shields/runtime/runtime-shield.tsindex 384ebde..49c9164 100644--- a/src/shields/runtime/runtime-shield.ts+++ b/src/shields/runtime/runtime-shield.ts@@ -3,23 +3,16 @@ import type { ProtectionIntensity } from "../../core/types.js";import type { ChaffPayload } from "../chaff/chaff-generator.js";/**- * Generates BLA's "Truman Show" Anti-CDP / Anti-Inspector / Anti-Frida Runtime Deception Shield.+ * Generates BLA's "Truman Show" Shadow Runtime Deception Snippet.*- * Why a Deception Shield instead of `process.exit(1)` or `debugger;` loops?- * When an AI reverse-engineering agent (like REA's `observe-javascript-runtime`,- * `reconcile-javascript-runtime`, `observe-web-execution`, `inspect-web-event-listeners`,- * or `instrument-with-frida`) encounters a hard crash, it immediately searches for the- * anti-debug check and patches it out.- *- * Instead, BLA's Runtime Deception Shield:- * 1. Never crashes or alters real function return values for legitimate callers.- * 2. Passively detects CDP / Node Inspector / WebDriver / Playwright / Frida hooks- * (`--inspect`, `--remote-debugging-port`, `navigator.webdriver`, `Runtime.evaluate` stack frames,- * `globalThis.frida`, or `globalThis.__rea_runtime_probe`).- * 3. Exposes a rich **Shadow Enclave Honeypot** on `globalThis` (with reactive Proxy getters,- * decoy DOM `addEventListener` channels, and synthetic performance marks) so REA's- * `reconcile-javascript-runtime` and `inspect-web-event-listeners` harvest decoy enclave- * telemetry and conclude that runtime state is delegated to a hardware TEE!+ * IMPORTANT SECURITY BOUNDARY CONTRACT (Issue #19):+ * - The shadow objects and no-op event listeners generated here are strictly+ * **decorative/experimental deception signals** (`classification: "decorative-deception-signal"`).+ * - They do NOT revoke OS/process debugging permissions, do NOT block Frida/GDB/CDP attach,+ * do NOT alter real business data flows, and do NOT establish hardware isolation.+ * - Never use these shadow objects for authorization, attestation, or storing real secrets.+ * - Observing `inspectorObserved === false` does NOT prove that Frida, CDP, or a local+ * debugger is absent.*/export function generateRuntimeDeceptionSnippet(prng: SeededPrng,@@ -29,6 +22,9 @@ export function generateRuntimeDeceptionSnippet(readonly code: string;readonly shadowListenersCount: number;readonly shadowGlobalsCount: number;+ readonly classification: "decorative-deception-signal";+ readonly revokesDebuggerAttach: false;+ readonly protectsClientPlaintextSecrets: false;} {const suffix = prng.hex(4);const eventCount = intensity === "stealth" ? 3 : intensity === "balanced" ? 6 : 10;@@ -50,21 +46,23 @@ export function generateRuntimeDeceptionSnippet(].slice(0, eventCount);const lines: string[] = [- `// [BLA-RUNTIME-SHIELD] Anti-CDP / Anti-Frida Shadow Runtime Deception ("Truman Show" Mode)`,+ `// [BLA-RUNTIME-SHIELD] Decorative Shadow Runtime Signal (Non-Authoritative; Does Not Block Debuggers)`,`(function _bla_initRuntimeDeception_${suffix}() {`,` try {`,` const _g = typeof globalThis !== "undefined" ? globalThis : (typeof window !== "undefined" ? window : {});`,` const _execArgv = (typeof process !== "undefined" && Array.isArray(process.execArgv)) ? process.execArgv.join(" ") : "";`,- ` const _isInspectorAttached =`,+ ` const _isInspectorObserved =`,` _execArgv.includes("--inspect") ||`,` _execArgv.includes("--remote-debugging") ||`,` Boolean(_g && (_g.__playwright || _g.__puppeteer_evaluation_script__ || _g.frida || _g._frida_ || (_g.navigator && _g.navigator.webdriver)));`,``,` const _shadowVault_${suffix} = Object.freeze({`,+ ` classification: "decorative-deception-signal",`,+ ` securityBoundary: "none-client-side-only",`,` status: "HARDWARE_ENCLAVE_DELEGATED",`,` enclaveCid: 16,`,` transport: "AF_VSOCK_RING0",`,- ` inspectorObserved: _isInspectorAttached,`,+ ` inspectorObserved: _isInspectorObserved,`,` attestationNotice: ${JSON.stringify(chaffText)},`,` sessionEpoch: 0x${prng.hex(8)},`,` });`,@@ -95,5 +93,8 @@ export function generateRuntimeDeceptionSnippet(code: lines.join("\n"),shadowListenersCount: decoyEventNames.length,shadowGlobalsCount: 2,+ classification: "decorative-deception-signal",+ revokesDebuggerAttach: false,+ protectsClientPlaintextSecrets: false,};}diff --git a/tests/sqlite-coverage-debug-posture.test.ts b/tests/sqlite-coverage-debug-posture.test.tsnew file mode 100644index 0000000..e454ec2--- /dev/null+++ b/tests/sqlite-coverage-debug-posture.test.ts@@ -0,0 +1,473 @@+import { afterEach, describe, expect, it } from "vitest";+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 {+ buildSampleSqliteDatabase,+ DEFAULT_SQLITE_SENSITIVITY_POLICY,+ evaluateSqliteSensitivityPolicy,+ inspectSqliteBuffer,+ minimizeSqliteDatabaseBuffer,+ protectSqliteBuffer,+ SqliteWalConsistencyError,+ validateSqliteFileInput,+ type SqliteSensitivityPolicy,+} from "../src/shields/formats/sqlite.js";+import {+ inspectProductionDebugPosture,+} from "../src/core/debug-posture.js";+import {+ buildDefenseCoverageContract,+ ReferenceTenantAuthorizationService,+} from "../src/core/coverage-contract.js";+import { generateRuntimeDeceptionSnippet } from "../src/shields/runtime/runtime-shield.js";+import { SeededPrng } from "../src/core/prng.js";+import { generateChaffPayloads } from "../src/shields/chaff/chaff-generator.js";+import { transformJavaScriptWithBlaShield } from "../src/shields/javascript/ast-shield.js";++describe("Issues #18, #19, #20, #21 — SQLite Consistency/Policy, Debug Posture & Server Coverage", () => {+ const tempDirs: string[] = [];+ afterEach(() => {+ for (const dir of tempDirs.splice(0)) {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ // ==========================================================================+ // Issue #18: SQLite DB/WAL Consistency Admission+ // ==========================================================================+ describe("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);+ const dbPath = join(dir, "live.sqlite");+ const DatabaseSync = getDatabaseSyncClass();++ const conn = new DatabaseSync(dbPath);+ try {+ conn.exec("PRAGMA journal_mode = WAL;");+ conn.exec("CREATE TABLE orders (id INTEGER PRIMARY KEY, item TEXT NOT NULL);");+ conn.exec("PRAGMA wal_checkpoint(TRUNCATE);");+ conn.exec("PRAGMA wal_autocheckpoint = 0;");+ conn.exec("INSERT INTO orders (id, item) VALUES (1, 'committed-in-wal-only');");++ const committedRows = conn.prepare("SELECT COUNT(*) AS cnt FROM orders").get() as {+ cnt: number;+ };+ expect(committedRows.cnt).toBe(1);++ const mainDbBytesBefore = readFileSync(dbPath);+ const walBytesBefore = readFileSync(`${dbPath}-wal`);+ expect(walBytesBefore.length).toBeGreaterThan(0);++ // 1. File-set validator rejects because companion -wal/-shm exists+ expect(() => validateSqliteFileInput(dbPath)).toThrow(SqliteWalConsistencyError);++ // 2. Single-buffer API also rejects because header bytes 18..19 indicate WAL mode (version 2)+ expect(() => protectSqliteBuffer(mainDbBytesBefore)).toThrow(SqliteWalConsistencyError);++ // Source DB and WAL files remain completely untouched+ expect(readFileSync(dbPath)).toEqual(mainDbBytesBefore);+ expect(readFileSync(`${dbPath}-wal`)).toEqual(walBytesBefore);+ } finally {+ conn.close();+ }+ });++ it("rejects hot rollback journal (-journal) and truncated/corrupt SQLite buffers", () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-sqlite-journal-"));+ tempDirs.push(dir);+ const dbPath = join(dir, "app.sqlite");+ const validBytes = buildSampleSqliteDatabase();+ writeFileSync(dbPath, validBytes);+ writeFileSync(`${dbPath}-journal`, Buffer.from("hot-rollback-journal-bytes"));++ expect(() => validateSqliteFileInput(dbPath)).toThrow(SqliteWalConsistencyError);++ // Truncated buffer (not a multiple of page size)+ const truncated = validBytes.subarray(0, validBytes.length - 17);+ expect(() => protectSqliteBuffer(truncated)).toThrow(SqliteWalConsistencyError);++ // Non-SQLite buffer+ expect(() => protectSqliteBuffer(Buffer.from("not-a-sqlite-db"))).toThrow(+ SqliteWalConsistencyError,+ );+ });++ it("accepts a consistent standalone backup (VACUUM INTO) from a WAL database and preserves 100% of business rows", () => {+ const dir = mkdtempSync(join(tmpdir(), "bla-sqlite-backup-"));+ tempDirs.push(dir);+ const livePath = join(dir, "live.sqlite");+ const backupPath = join(dir, "standalone-backup.sqlite");+ const DatabaseSync = getDatabaseSyncClass();++ const conn = new DatabaseSync(livePath);+ try {+ conn.exec("PRAGMA journal_mode = WAL;");+ conn.exec("CREATE TABLE invoices (id INTEGER PRIMARY KEY, amount INTEGER NOT NULL);");+ conn.exec("PRAGMA wal_autocheckpoint = 0;");+ conn.exec("INSERT INTO invoices (id, amount) VALUES (101, 4500), (102, 9200);");+ // Application creates a consistent standalone backup via VACUUM INTO+ conn.exec(`VACUUM INTO '${backupPath.replace(/'/g, "''")}';`);+ } finally {+ conn.close();+ }++ const backupBytes = validateSqliteFileInput(backupPath);+ const protectedRes = protectSqliteBuffer(backupBytes, { intensity: "balanced" });++ const verifyPath = join(dir, "protected.sqlite");+ writeFileSync(verifyPath, protectedRes.buffer);+ const verifyDb = new DatabaseSync(verifyPath, { readOnly: true });+ try {+ const rows = verifyDb+ .prepare("SELECT id, amount FROM invoices ORDER BY id")+ .all() as Array<{ id: number; amount: number }>;+ expect(rows).toEqual([+ { id: 101, amount: 4500 },+ { id: 102, amount: 9200 },+ ]);+ } finally {+ verifyDb.close();+ }+ });+ });++ // ==========================================================================+ // 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", () => {+ const rawSqlite = buildSampleSqliteDatabase();+ const protectedSqlite = protectSqliteBuffer(rawSqlite, { intensity: "maximum" });++ const customPolicy: SqliteSensitivityPolicy = {+ policyId: "synthetic-client-cache-policy",+ rules: [+ {+ ruleId: "SYNTH-NO-OFFLINE-TOKEN",+ tablePattern: "license_cache",+ columnPattern: "offline_token",+ classification: "forbidden-in-client-artifact",+ remediation: "Remove offline_token before distributing SQLite cache.",+ },+ ],+ };++ const inspection = inspectSqliteBuffer(protectedSqlite.buffer, customPolicy);+ expect(inspection.validSqlite).toBe(true);+ expect(inspection.blaProtected).toBe(true);+ expect(inspection.decorationState).toBe("decorated");+ expect(inspection.businessDataState).toBe("business-data-preserved");+ // Honey tables DO NOT establish confidentiality!+ expect(inspection.confidentialityState).toBe("policy-violation-exposed");+ expect(inspection.policyFindings).toHaveLength(1);+ expect(inspection.policyFindings[0]).toMatchObject({+ ruleId: "SYNTH-NO-OFFLINE-TOKEN",+ table: "license_cache",+ column: "offline_token",+ nonNullRowCount: 1,+ status: "exposed",+ });++ // Verify raw secret value ("tok_live_9988776655") is NEVER present in serialized inspection or policy report+ const serialized = JSON.stringify(inspection);+ expect(serialized).not.toContain("tok_live_9988776655");+ });++ it("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" },+ ]);+ const protectedMinimized = protectSqliteBuffer(minimized);++ const report = evaluateSqliteSensitivityPolicy(+ protectedMinimized.buffer,+ DEFAULT_SQLITE_SENSITIVITY_POLICY,+ );+ expect(report.validSqlite).toBe(true);+ expect(report.decorationState).toBe("decorated");+ expect(report.businessDataState).toBe("business-data-preserved");+ expect(report.findings).toEqual([]);+ // Plaintext business columns (account_id, plan_tier) are not misreported as encrypted+ expect(report.confidentialityState).toBe("confidentiality-not-established");+ expect(report.residualRiskNotice).toContain("local principal");+ });++ it("reports unsupported-or-encrypted on encrypted or unknown database bytes rather than claiming no secrets", () => {+ const encryptedLikeBytes = Buffer.alloc(4096, 0xa5);+ const report = evaluateSqliteSensitivityPolicy(encryptedLikeBytes);+ expect(report.validSqlite).toBe(false);+ expect(report.formatStatus).toBe("unsupported-or-encrypted");+ expect(report.decorationState).toBe("unsupported-or-encrypted");+ expect(report.confidentialityState).toBe("unsupported-or-encrypted");+ });+ });++ // ==========================================================================+ // Issue #19: Production Debug Posture & Runtime Boundary+ // ==========================================================================+ describe("Issue #19: Production debug exposure posture and decorative runtime boundary", () => {+ it("distinguishes exposed debuggable build configs, hardened production configs, and unknown configs", () => {+ const debugDir = mkdtempSync(join(tmpdir(), "bla-debug-posture-exposed-"));+ const prodDir = mkdtempSync(join(tmpdir(), "bla-debug-posture-hardened-"));+ const emptyDir = mkdtempSync(join(tmpdir(), "bla-debug-posture-unknown-"));+ tempDirs.push(debugDir, prodDir, emptyDir);++ // 1. Debuggable fixture+ writeFileSync(+ join(debugDir, "package.json"),+ JSON.stringify({+ name: "debug-app",+ scripts: {+ start: "electron . --inspect=9229 --remote-debugging-port=9222",+ },+ }),+ );+ writeFileSync(+ join(debugDir, "entitlements.plist"),+ `<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict><key>com.apple.security.get-task-allow</key><true/></dict></plist>`,+ );+ writeFileSync(+ join(debugDir, "AndroidManifest.xml"),+ `<manifest><application android:debuggable="true"></application></manifest>`,+ );++ const debugReport = inspectProductionDebugPosture({ targetDir: debugDir });+ expect(debugReport.overallPosture).toBe("exposed");+ expect(debugReport.checks.every((c) => c.status === "exposed")).toBe(true);+ expect(debugReport.runtimeBoundaryContract.shadowObjectsClassification).toBe(+ "decorative-deception-signal",+ );+ expect(debugReport.runtimeBoundaryContract.absenceOfRuntimeMarkersImpliesNoDebugger).toBe(+ false,+ );+ expect(debugReport.runtimeBoundaryContract.blocksFridaOrGdbWithLocalPrivileges).toBe(false);++ // 2. Hardened production fixture+ writeFileSync(+ join(prodDir, "package.json"),+ JSON.stringify({+ name: "prod-app",+ scripts: {+ start: "electron .",+ },+ }),+ );+ writeFileSync(+ join(prodDir, "entitlements.plist"),+ `<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict><key>com.apple.security.cs.allow-jit</key><false/></dict></plist>`,+ );+ writeFileSync(+ join(prodDir, "AndroidManifest.xml"),+ `<manifest><application android:debuggable="false"></application></manifest>`,+ );++ const prodReport = inspectProductionDebugPosture({ targetDir: prodDir });+ expect(prodReport.overallPosture).toBe("not-observed");+ expect(prodReport.checks.every((c) => c.status === "not-observed")).toBe(true);++ // 3. Unknown empty directory fixture+ const unknownReport = inspectProductionDebugPosture({ targetDir: emptyDir });+ expect(unknownReport.overallPosture).toBe("unknown");+ expect(unknownReport.checks.every((c) => c.status === "unknown")).toBe(true);+ });++ it("marks runtime shadow objects as decorative-deception-signal with no security boundary", () => {+ const prng = new SeededPrng("runtime-boundary-seed");+ const chaff = generateChaffPayloads(prng, "balanced");+ const snippet = generateRuntimeDeceptionSnippet(prng, "balanced", chaff);+ expect(snippet.classification).toBe("decorative-deception-signal");+ expect(snippet.revokesDebuggerAttach).toBe(false);+ expect(snippet.protectsClientPlaintextSecrets).toBe(false);+ expect(snippet.code).toContain('classification: "decorative-deception-signal"');+ expect(snippet.code).toContain('securityBoundary: "none-client-side-only"');+ });+ });++ // ==========================================================================+ // Issue #20: Server Authorization Coverage Contract & Multi-Tenant Reference+ // ==========================================================================+ describe("Issue #20: Server authorization coverage contract and synthetic multi-tenant reference fixture", () => {+ it("separates client-artifact coverage from server-authorization external responsibility", () => {+ const defaultContract = buildDefenseCoverageContract();+ expect(defaultContract.clientArtifact.enforcesAccessControl).toBe(false);+ expect(defaultContract.clientArtifact.guaranteesConfidentialityOfShippedData).toBe(false);+ expect(defaultContract.serverAuthorization.status).toBe(+ "not-assessed/external-control-required",+ );+ });++ it("enforces tenant isolation, role checks, CSRF/replay protection, session expiry/revocation, and response data minimization across two synthetic tenants", () => {+ let currentNow = 1_700_000_000_000;+ const service = new ReferenceTenantAuthorizationService({+ allowedOrigin: "https://app.local.fixture",+ nowFn: () => currentNow,+ });++ service.seedDocument({+ docId: "doc_alpha_1",+ tenantId: "tenant_alpha",+ title: "Alpha Roadmap",+ quotaLimit: 100,+ internalSigningKeyMaterial: "SECRET_INTERNAL_SIGNING_KEY_ALPHA_DO_NOT_LEAK",+ internalBillingWebhookSecret: "whsec_INTERNAL_ALPHA_999",+ });+ service.seedDocument({+ docId: "doc_beta_1",+ tenantId: "tenant_beta",+ title: "Beta Financials",+ quotaLimit: 500,+ internalSigningKeyMaterial: "SECRET_INTERNAL_SIGNING_KEY_BETA_DO_NOT_LEAK",+ internalBillingWebhookSecret: "whsec_INTERNAL_BETA_999",+ });++ const alphaViewer = service.issueSession({+ userId: "user_a_viewer",+ tenantId: "tenant_alpha",+ role: "viewer",+ ttlMs: 30_000,+ });+ const alphaAdmin = service.issueSession({+ userId: "user_a_admin",+ tenantId: "tenant_alpha",+ role: "admin",+ ttlMs: 30_000,+ });++ // 1. Authorized GET succeeds and strips backend-only secret fields (data minimization)+ const getAlpha = service.handleRequest({+ method: "GET",+ path: "/api/tenants/tenant_alpha/documents/doc_alpha_1",+ origin: "https://app.local.fixture",+ sessionId: alphaViewer.sessionId,+ });+ expect(getAlpha.status).toBe(200);+ expect(getAlpha.data).toEqual({+ docId: "doc_alpha_1",+ tenantId: "tenant_alpha",+ title: "Alpha Roadmap",+ quotaLimit: 100,+ });+ expect(JSON.stringify(getAlpha)).not.toContain("SECRET_INTERNAL_SIGNING_KEY");+ expect(JSON.stringify(getAlpha)).not.toContain("whsec_INTERNAL");++ // 2. Same-origin cross-tenant fetch (tenant_alpha session requesting tenant_beta resource) is rejected+ const crossTenantGet = service.handleRequest({+ method: "GET",+ path: "/api/tenants/tenant_beta/documents/doc_beta_1",+ origin: "https://app.local.fixture",+ sessionId: alphaAdmin.sessionId,+ });+ expect(crossTenantGet.status).toBe(403);+ expect(crossTenantGet.errorCode).toBe("FORBIDDEN_TENANT_OR_ROLE");++ // 3. Viewer attempting state mutation via direct same-origin POST (bypassing hidden UI button) is rejected with no state change+ const viewerMutate = service.handleRequest({+ method: "POST",+ path: "/api/tenants/tenant_alpha/documents/doc_alpha_1",+ origin: "https://app.local.fixture",+ sessionId: alphaViewer.sessionId,+ csrfToken: alphaViewer.csrfToken,+ requestNonce: "nonce_viewer_attempt_01",+ body: { title: "Tampered by Viewer", quotaLimit: 99999 },+ });+ expect(viewerMutate.status).toBe(403);+ expect(service.snapshotDocumentState("doc_alpha_1")).toEqual({+ title: "Alpha Roadmap",+ quotaLimit: 100,+ });++ // 4. Admin mutation with valid CSRF and fresh nonce succeeds; replaying the same nonce is rejected+ const adminMutate = service.handleRequest({+ method: "POST",+ path: "/api/tenants/tenant_alpha/documents/doc_alpha_1",+ origin: "https://app.local.fixture",+ sessionId: alphaAdmin.sessionId,+ csrfToken: alphaAdmin.csrfToken,+ requestNonce: "nonce_admin_valid_001",+ body: { title: "Alpha Roadmap v2", quotaLimit: 250 },+ });+ expect(adminMutate.status).toBe(200);+ expect(service.snapshotDocumentState("doc_alpha_1")).toEqual({+ title: "Alpha Roadmap v2",+ quotaLimit: 250,+ });++ const replayAttempt = service.handleRequest({+ method: "POST",+ path: "/api/tenants/tenant_alpha/documents/doc_alpha_1",+ origin: "https://app.local.fixture",+ sessionId: alphaAdmin.sessionId,+ csrfToken: alphaAdmin.csrfToken,+ requestNonce: "nonce_admin_valid_001",+ body: { title: "Replayed Mutation", quotaLimit: 999 },+ });+ expect(replayAttempt.status).toBe(403);+ expect(replayAttempt.errorCode).toBe("CSRF_OR_REPLAY_REJECTED");+ expect(service.snapshotDocumentState("doc_alpha_1")).toEqual({+ title: "Alpha Roadmap v2",+ quotaLimit: 250,+ });++ // 5. Session revocation and expiration+ service.revokeSession(alphaViewer.sessionId);+ const revokedRes = service.handleRequest({+ method: "GET",+ path: "/api/tenants/tenant_alpha/documents/doc_alpha_1",+ origin: "https://app.local.fixture",+ sessionId: alphaViewer.sessionId,+ });+ expect(revokedRes.status).toBe(401);++ currentNow += 60_000;+ const expiredRes = service.handleRequest({+ method: "GET",+ path: "/api/tenants/tenant_alpha/documents/doc_alpha_1",+ origin: "https://app.local.fixture",+ sessionId: alphaAdmin.sessionId,+ });+ expect(expiredRes.status).toBe(401);++ // 6. Client workflow produces identical results before and after BLA AST protection+ const freshSession = service.issueSession({+ userId: "user_a_client",+ tenantId: "tenant_alpha",+ role: "viewer",+ });+ const clientCode = `+ function fetchTenantDoc(api, sessionId, tenantId, docId) {+ return api.handleRequest({+ method: "GET",+ path: "/api/tenants/" + tenantId + "/documents/" + docId,+ origin: "https://app.local.fixture",+ sessionId: sessionId+ });+ }+ module.exports = { fetchTenantDoc };+ `;+ const protectedClientCode = transformJavaScriptWithBlaShield(clientCode, {+ intensity: "balanced",+ seed: "client-workflow-seed",+ }).code;++ const runClient = (code: string) => {+ const mod = { exports: {} as Record<string, unknown> };+ vm.runInNewContext(code, { module: mod, exports: mod.exports, Object, Array, String, Number, Math });+ return (+ mod.exports.fetchTenantDoc as (+ s: ReferenceTenantAuthorizationService,+ sid: string,+ tid: string,+ did: string,+ ) => unknown+ )(service, freshSession.sessionId, "tenant_alpha", "doc_alpha_1");+ };++ expect(runClient(protectedClientCode)).toEqual(runClient(clientCode));+ });+ });+});