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.

refactor(engine): share one bounded directory walker across discovery and lints

DeryFerdab6f971b3616
diff --git a/src/core/walk.ts b/src/core/walk.ts
new file mode 100644
index 0000000..a79c038
--- /dev/null
+++ b/src/core/walk.ts
@@ -0,0 +1,83 @@
+import { readdirSync, statSync } from "node:fs";
+import { join } from "node:path";
+
+export interface BoundedWalkOptions {
+ /** Maximum directory depth to descend (root = 0). */
+ readonly maxDepth: number;
+ /** Stop after this many accepted files. Use Number.MAX_SAFE_INTEGER for no cap. */
+ readonly maxFiles: number;
+ readonly skipDirs?: ReadonlySet<string>;
+ /** Skip directories whose name starts with "." (hidden files are still allowed). */
+ readonly skipHiddenDirs?: boolean;
+ /** Sort directory entries by name for stable, platform-independent paging. */
+ readonly sortEntries?: boolean;
+ /**
+ * Descend into a directory at exactly `maxDepth`. Default true. Set false to
+ * match walkers that treat `maxDepth` as the last depth they inspect.
+ */
+ readonly descendAtMaxDepth?: boolean;
+ /** When set, files larger than this are skipped (requires an extra stat). */
+ readonly maxFileBytes?: number;
+ /** Final filter; called only for regular files before they are pushed. */
+ readonly accept?: (fullPath: string, name: string) => boolean;
+}
+
+/**
+ * Bounded, symlink-safe directory walk shared by discovery and packaging lints.
+ * Directory symlinks are not descended because `Dirent.isDirectory()` is false
+ * for them, and read errors are treated as an empty directory.
+ */
+export function walkBounded(root: string, options: BoundedWalkOptions): string[] {
+ const out: string[] = [];
+ const {
+ maxDepth,
+ maxFiles,
+ skipDirs,
+ skipHiddenDirs = false,
+ sortEntries = false,
+ descendAtMaxDepth = true,
+ maxFileBytes,
+ accept,
+ } = options;
+
+ const visit = (dir: string, depth: number): void => {
+ if (out.length >= maxFiles || depth > maxDepth) return;
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ if (sortEntries) {
+ entries = entries.slice().sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
+ }
+ for (const entry of entries) {
+ if (out.length >= maxFiles) return;
+ if (entry.isDirectory()) {
+ if (skipDirs?.has(entry.name)) continue;
+ if (skipHiddenDirs && entry.name.startsWith(".")) continue;
+ if (!descendAtMaxDepth && depth >= maxDepth) continue;
+ visit(join(dir, entry.name), depth + 1);
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ const full = join(dir, entry.name);
+ if (maxFileBytes !== undefined) {
+ let size: number;
+ try {
+ const stat = statSync(full);
+ if (!stat.isFile()) continue;
+ size = stat.size;
+ } catch {
+ continue;
+ }
+ if (size > maxFileBytes) continue;
+ }
+ if (accept !== undefined && !accept(full, entry.name)) continue;
+ out.push(full);
+ }
+ };
+
+ visit(root, 0);
+ return out;
+}
\ No newline at end of file
diff --git a/src/engine/harden.ts b/src/engine/harden.ts
index 971c3a4..6bc082c 100644
--- a/src/engine/harden.ts
+++ b/src/engine/harden.ts
@@ -1,13 +1,13 @@
import {
existsSync,
mkdirSync,
- readdirSync,
readFileSync,
statSync,
writeFileSync,
} from "node:fs";
import { basename, dirname, join, relative, resolve, sep } from "node:path";
import { detectArtifactFormat } from "../core/detector.js";
+import { walkBounded } from "../core/walk.js";
import type { ArtifactFormat, ProtectionIntensity } from "../core/types.js";
import { BLA_IDENTITY } from "../identity.js";
import {
@@ -287,50 +287,38 @@ function resolveSearchRoots(absRoot: string): {
return { preferred, includeProjectRootSupplemental: true };
}
-function walkCollect(
- dir: string,
+function collectRootArtifacts(
root: string,
- depth: number,
- out: DiscoveredArtifact[],
+ projectRoot: string,
maxArtifacts: number,
- skipDirs: ReadonlySet<string> = SKIP_DIR_NAMES,
-): void {
- if (out.length >= maxArtifacts || depth > MAX_WALK_DEPTH) return;
- let entries;
- try {
+ skipDirs: ReadonlySet<string>,
+): DiscoveredArtifact[] {
+ const formats = new Map<string, ArtifactFormat>();
+ const files = walkBounded(root, {
+ maxDepth: MAX_WALK_DEPTH,
+ maxFiles: maxArtifacts,
+ skipDirs,
+ skipHiddenDirs: true,
// Locale-independent name sort so offset paging is stable across platforms.
- entries = readdirSync(dir, { withFileTypes: true }).slice().sort((a, b) =>
- a.name < b.name ? -1 : a.name > b.name ? 1 : 0,
- );
- } catch {
- return;
- }
- for (const entry of entries) {
- if (out.length >= maxArtifacts) return;
- if (entry.name.startsWith(".") && entry.name !== ".asar") {
- // Still allow probing files that begin with '.', but skip hidden dirs.
- if (entry.isDirectory()) continue;
- }
- if (entry.isDirectory()) {
- if (skipDirs.has(entry.name)) continue;
- walkCollect(join(dir, entry.name), root, depth + 1, out, maxArtifacts, skipDirs);
- continue;
- }
- const full = join(dir, entry.name);
- const format = detectArtifactFormat(full);
- if (!isProtectableFormat(format)) continue;
- // Skip already-shielded outputs to avoid re-hardening loops.
- if (/\.shielded(\.|$)/i.test(entry.name)) continue;
- if (entry.name.endsWith(".bla-manifest.json")) continue;
- if (entry.name.endsWith(".bunfs-snapshot")) continue;
- out.push({
- path: full,
- format,
- // Normalize to POSIX separators so reports, manifests, and MCP
- // structuredContent stay platform-independent (`dist/app.js`).
- relativePath: (relative(root, full) || basename(full)).split(sep).join("/"),
- });
- }
+ sortEntries: true,
+ accept: (full, name) => {
+ const format = detectArtifactFormat(full);
+ if (!isProtectableFormat(format)) return false;
+ // Skip already-shielded outputs to avoid re-hardening loops.
+ if (/\.shielded(\.|$)/i.test(name)) return false;
+ if (name.endsWith(".bla-manifest.json")) return false;
+ if (name.endsWith(".bunfs-snapshot")) return false;
+ formats.set(full, format);
+ return true;
+ },
+ });
+ return files.map((full) => ({
+ path: full,
+ format: formats.get(full) ?? detectArtifactFormat(full),
+ // Normalize to POSIX separators so reports, manifests, and MCP
+ // structuredContent stay platform-independent (`dist/app.js`).
+ relativePath: (relative(projectRoot, full) || basename(full)).split(sep).join("/"),
+ }));
}
/**
@@ -396,10 +384,14 @@ function collectHardenableArtifacts(
const found: DiscoveredArtifact[] = [];
const { preferred, includeProjectRootSupplemental } = resolveSearchRoots(abs);
for (const root of preferred) {
- walkCollect(root, abs, 0, found, maxArtifacts, SKIP_DIR_NAMES);
+ const remaining = maxArtifacts - found.length;
+ if (remaining <= 0) break;
+ found.push(...collectRootArtifacts(root, abs, remaining, SKIP_DIR_NAMES));
}
- if (includeProjectRootSupplemental) {
- walkCollect(abs, abs, 0, found, maxArtifacts, SUPPLEMENTAL_SKIP_DIR_NAMES);
+ if (includeProjectRootSupplemental && found.length < maxArtifacts) {
+ found.push(
+ ...collectRootArtifacts(abs, abs, maxArtifacts - found.length, SUPPLEMENTAL_SKIP_DIR_NAMES),
+ );
}
// De-dupe by absolute path (cargo release may overlap target/)
const seen = new Set<string>();
diff --git a/src/engine/lane-independence-lint.ts b/src/engine/lane-independence-lint.ts
index 9449d10..cb06925 100644
--- a/src/engine/lane-independence-lint.ts
+++ b/src/engine/lane-independence-lint.ts
@@ -12,8 +12,9 @@
*/
-import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
-import { join, resolve } from "node:path";
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { resolve } from "node:path";
+import { walkBounded } from "../core/walk.js";
export const LANE_INDEPENDENCE_SCHEMA = "bla-lane-independence-lint/v1" as const;
@@ -184,25 +185,14 @@ const JS_EXT = /\.(?:[cm]?[jt]s|tsx?)$/i;
const MAX_JS_FILES = 64;
const MAX_WALK_DEPTH = 8;
-function walkJsGateCandidates(dir: string, depth: number, out: string[]): void {
- if (out.length >= MAX_JS_FILES || depth > MAX_WALK_DEPTH) return;
- let entries;
- try {
- entries = readdirSync(dir, { withFileTypes: true });
- } catch {
- return;
- }
- for (const entry of entries) {
- if (out.length >= MAX_JS_FILES) return;
- if (entry.isDirectory()) {
- if (SKIP_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
- walkJsGateCandidates(join(dir, entry.name), depth + 1, out);
- continue;
- }
- if (!entry.isFile()) continue;
- if (!JS_EXT.test(entry.name)) continue;
- out.push(join(dir, entry.name));
- }
+function walkJsGateCandidates(dir: string): string[] {
+ return walkBounded(dir, {
+ maxDepth: MAX_WALK_DEPTH,
+ maxFiles: MAX_JS_FILES,
+ skipDirs: SKIP_DIR_NAMES,
+ skipHiddenDirs: true,
+ accept: (_full, name) => JS_EXT.test(name),
+ });
}
/** File wrapper matching other packaging lints. */
@@ -232,7 +222,6 @@ export function discoverAndLintLaneIndependence(
if (st.isFile()) {
return [lintLaneIndependenceFile(abs)];
}
- const candidates: string[] = [];
- walkJsGateCandidates(abs, 0, candidates);
+ const candidates = walkJsGateCandidates(abs);
return candidates.map((p) => lintLaneIndependenceFile(p));
}
diff --git a/src/engine/polymorph-report.ts b/src/engine/polymorph-report.ts
index 9987b41..5ee935c 100644
--- a/src/engine/polymorph-report.ts
+++ b/src/engine/polymorph-report.ts
@@ -10,11 +10,11 @@
import { createHash } from "node:crypto";
import {
existsSync,
- readdirSync,
readFileSync,
statSync,
} from "node:fs";
-import { extname, join, relative, resolve, sep } from "node:path";
+import { extname, relative, resolve, sep } from "node:path";
+import { walkBounded } from "../core/walk.js";
import { inspectWasmBinary } from "../shields/formats/wasm.js";
export const POLYMORPH_REPORT_SCHEMA = "bla-polymorph-report/v1" as const;
@@ -95,35 +95,17 @@ export interface PolymorphReport {
}
function walkFiles(root: string, maxDepth = 8): string[] {
- const abs = resolve(root);
- const out: string[] = [];
- const stack: Array<{ dir: string; depth: number }> = [{ dir: abs, depth: 0 }];
- while (stack.length > 0) {
- const { dir, depth } = stack.pop()!;
- let entries;
- try {
- entries = readdirSync(dir, { withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of entries) {
- if (ent.name.startsWith(".") && ent.name !== ".blarc") {
- // keep walking into non-dot; skip hidden dirs except we already filter
- }
- const full = join(dir, ent.name);
- if (ent.isDirectory()) {
- if (SKIP_DIR_NAMES.has(ent.name) || depth >= maxDepth) continue;
- if (ent.name.startsWith(".")) continue;
- stack.push({ dir: full, depth: depth + 1 });
- } else if (ent.isFile()) {
- if (SKIP_BASENAMES.has(ent.name)) continue;
- const ext = extname(ent.name).toLowerCase();
- if (!COMPARE_EXTS.has(ext)) continue;
- out.push(full);
- }
- }
- }
- return out.sort();
+ return walkBounded(resolve(root), {
+ maxDepth,
+ maxFiles: Number.MAX_SAFE_INTEGER,
+ skipDirs: SKIP_DIR_NAMES,
+ skipHiddenDirs: true,
+ descendAtMaxDepth: false,
+ accept: (_full, name) => {
+ if (SKIP_BASENAMES.has(name)) return false;
+ return COMPARE_EXTS.has(extname(name).toLowerCase());
+ },
+ }).sort();
}
function relKey(root: string, absFile: string): string {
diff --git a/src/engine/seal-commitment-lint.ts b/src/engine/seal-commitment-lint.ts
index 94fd4d5..b118564 100644
--- a/src/engine/seal-commitment-lint.ts
+++ b/src/engine/seal-commitment-lint.ts
@@ -15,6 +15,7 @@
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { basename, join, resolve } from "node:path";
+import { walkBounded } from "../core/walk.js";
export const SEAL_COMMITMENT_SCHEMA = "bla-seal-commitment-lint/v1" as const;
@@ -345,29 +346,14 @@ export function lintSealCommitmentFile(filePath: string): SealCommitmentReport {
return lintSealCommitmentSource(source, { path: abs });
}
-function walkSealCandidates(
- dir: string,
- depth: number,
- out: string[],
-): void {
- if (out.length >= MAX_SEAL_FILES || depth > MAX_WALK_DEPTH) return;
- let entries;
- try {
- entries = readdirSync(dir, { withFileTypes: true });
- } catch {
- return;
- }
- for (const entry of entries) {
- if (out.length >= MAX_SEAL_FILES) return;
- if (entry.isDirectory()) {
- if (SKIP_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
- walkSealCandidates(join(dir, entry.name), depth + 1, out);
- continue;
- }
- if (!entry.isFile()) continue;
- if (!looksLikeSealFileName(entry.name)) continue;
- out.push(join(dir, entry.name));
- }
+function walkSealCandidates(dir: string): string[] {
+ return walkBounded(dir, {
+ maxDepth: MAX_WALK_DEPTH,
+ maxFiles: MAX_SEAL_FILES,
+ skipDirs: SKIP_DIR_NAMES,
+ skipHiddenDirs: true,
+ accept: (_full, name) => looksLikeSealFileName(name),
+ });
}
/**
@@ -384,8 +370,7 @@ export function discoverAndLintSealSidecars(
if (st.isFile()) {
return [lintSealCommitmentFile(abs)];
}
- const candidates: string[] = [];
- walkSealCandidates(abs, 0, candidates);
+ const candidates = walkSealCandidates(abs);
// Also check common build output folder names one level down even if skipped
// as deep roots — seal.json often sits next to dist artifacts at project root.
return candidates.map((p) => lintSealCommitmentFile(p));
diff --git a/src/engine/wasm-xor-mask-sidecar-lint.ts b/src/engine/wasm-xor-mask-sidecar-lint.ts
index 7ce52d6..6715386 100644
--- a/src/engine/wasm-xor-mask-sidecar-lint.ts
+++ b/src/engine/wasm-xor-mask-sidecar-lint.ts
@@ -16,8 +16,9 @@
*/
import { createHash, randomBytes } from "node:crypto";
-import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
-import { basename, join, resolve } from "node:path";
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { basename, resolve } from "node:path";
+import { walkBounded } from "../core/walk.js";
export const WASM_XOR_MASK_SIDECAR_SCHEMA = "bla-wasm-xor-mask-sidecar-lint/v1" as const;
@@ -346,34 +347,21 @@ export function wasmXorMaskSidecarRefuseMessage(
return `BLA refused bankrupt/maximum protect of ${p}: WASM XOR-mask sidecar entitlement pack (${ids || "exposed"}). Pass allowWasmXorMaskSidecar / --allow-wasm-xor-mask-sidecar / allow_wasm_xor_mask_sidecar to override. Prefer key-dependent unmask and one-way commitments (red/blue round-6).`;
}
-function walkWasmFiles(root: string, out: string[], depth: number): void {
- if (out.length >= MAX_WASM_FILES || depth > MAX_WALK_DEPTH) return;
- let entries: string[] = [];
- try {
- entries = readdirSync(root);
- } catch {
- return;
- }
- for (const name of entries) {
- if (out.length >= MAX_WASM_FILES) break;
- if (SKIP_DIR_NAMES.has(name)) continue;
- const full = join(root, name);
- let st;
- try {
- st = statSync(full);
- } catch {
- continue;
- }
- if (st.isDirectory()) walkWasmFiles(full, out, depth + 1);
- else if (st.isFile() && /\.wasm$/i.test(name) && st.size <= MAX_SCAN_BYTES) out.push(full);
- }
+function walkWasmFiles(root: string): string[] {
+ return walkBounded(root, {
+ maxDepth: MAX_WALK_DEPTH,
+ maxFiles: MAX_WASM_FILES,
+ skipDirs: SKIP_DIR_NAMES,
+ maxFileBytes: MAX_SCAN_BYTES,
+ accept: (_full, name) => /\.wasm$/i.test(name),
+ });
}
export function discoverAndLintWasmXorMaskSidecars(directory: string): WasmXorMaskSidecarReport[] {
const abs = resolve(directory);
const files: string[] = [];
if (existsSync(abs) && statSync(abs).isFile() && /\.wasm$/i.test(abs)) files.push(abs);
- else if (existsSync(abs) && statSync(abs).isDirectory()) walkWasmFiles(abs, files, 0);
+ else if (existsSync(abs) && statSync(abs).isDirectory()) files.push(...walkWasmFiles(abs));
return files.map((f) => lintWasmXorMaskSidecarFile(f));
}