fix(sqlite,engine): resolve .db false-positive detection and harden AST/config/manifest/lint gates

- Fix #130: require 'SQLite format 3\0' magic bytes for generic .db files while keeping .sqlite/.sqlite3 in the extension fallback so corrupt SQLite files still fail closed
- Skip non-SQLite .db files in weave-decoy candidate discovery so WeavePlan.overallStatus is not downgraded by opaque runtime state files
- Support WITHOUT ROWID tables and BigInt columns in SQLite snapshotBusinessTables
- Clean up newly created partial output directories when directory-mode protectTarget fails on a child artifact, skip symlinks, and forward all ProtectionOptions
- Fix #129: replace naive string splitting in encryptStrings with Babel AST span replacement, support 0-substitution backtick templates, and skip already-encrypted files
- Validate sidecarEntangle and requireAgentWeave in .blarc and validate existing config in resolveProjectSeed/initBlaConfig
- Exclude custom outputDirectory from discoverHardenTargets and reject project-root or .git/node_modules output directories
- Add plaintextSecrets, integrityCoverage, and bindScope to bla lint --json detailCounts and --allow-* flags to bla lint / bla_lint
- Verify adjacent regular-file or --artifact SHA-256 digests in bla verify-manifest
- Add scripts/verify-website.mjs covering all 7 HTML pages, CSP headers, and internal links/anchors

Fixes #129
Fixes #130

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
qybaihe
2026-11-08 21:14:07 +08:00
parent 8f1039173b
commit a2bda821c9
21 changed files with 856 additions and 103 deletions
+2 -22
View File
@@ -24,25 +24,5 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Verify required pages and assets exist
run: |
for f in \
website/index.html \
website/get-started/index.html \
website/showcase/index.html \
website/guides/index.html \
website/faq/index.html \
website/enterprise/index.html \
website/assets/styles.css \
website/assets/main.js \
website/assets/i18n.js \
website/assets/home.js \
website/assets/logo.png \
website/assets/favicon.png \
website/assets/favicon.svg \
website/assets/social-card.svg \
website/schemas/defense-manifest-v1.json \
website/schemas/bla.config.v1.json; do
test -f "$f" || (echo "Missing required website file: $f" && exit 1)
done
echo "All website pages and assets verified."
- name: Verify website pages, CSP headers, assets, and internal links
run: node scripts/verify-website.mjs
+8
View File
@@ -0,0 +1,8 @@
export interface WebsiteVerifyResult {
readonly ok: boolean;
readonly pagesChecked: number;
readonly linksChecked: number;
readonly errors: readonly string[];
}
export function verifyWebsiteDirectory(websiteRoot?: string): WebsiteVerifyResult;
+186
View File
@@ -0,0 +1,186 @@
#!/usr/bin/env node
import { existsSync, readFileSync, statSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const REQUIRED_HTML_PAGES = [
"index.html",
"get-started/index.html",
"showcase/index.html",
"crackme/index.html",
"guides/index.html",
"faq/index.html",
"enterprise/index.html",
];
const REQUIRED_ASSETS = [
"assets/styles.css",
"assets/main.js",
"assets/i18n.js",
"assets/home.js",
"assets/logo.png",
"assets/favicon.png",
"assets/favicon.svg",
"assets/social-card.svg",
"schemas/defense-manifest-v1.json",
"schemas/bla.config.v1.json",
];
function extractIds(html) {
const ids = new Set();
const re = /\bid\s*=\s*(?:"([^"]+)"|'([^']+)')/gi;
let m;
while ((m = re.exec(html)) !== null) {
ids.add(m[1] ?? m[2]);
}
return ids;
}
function extractCspContent(html) {
const metaRe = /<meta\b[^>]*http-equiv\s*=\s*(?:"Content-Security-Policy"|'Content-Security-Policy')[^>]*>/i;
const tag = metaRe.exec(html)?.[0];
if (!tag) return null;
const contentRe = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
const m = contentRe.exec(tag);
return m ? (m[1] ?? m[2] ?? "") : null;
}
function extractLocalRefs(html) {
const refs = [];
const re = /\b(?:href|src)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
let m;
while ((m = re.exec(html)) !== null) {
const val = (m[1] ?? m[2] ?? "").trim();
if (
!val ||
val.startsWith("http://") ||
val.startsWith("https://") ||
val.startsWith("mailto:") ||
val.startsWith("data:") ||
val.startsWith("javascript:")
) {
continue;
}
refs.push(val);
}
return refs;
}
/**
* Verify all static website HTML pages, assets, CSP headers, and internal links/anchors.
*
* @param {string} [websiteRoot]
* @returns {{ ok: boolean, pagesChecked: number, linksChecked: number, errors: string[] }}
*/
export function verifyWebsiteDirectory(websiteRoot = resolve(REPO_ROOT, "website")) {
const absRoot = resolve(websiteRoot);
const errors = [];
let pagesChecked = 0;
let linksChecked = 0;
for (const rel of REQUIRED_ASSETS) {
const full = resolve(absRoot, rel);
if (!existsSync(full) || !statSync(full).isFile()) {
errors.push(`Missing required asset: ${rel}`);
}
}
const pageCache = new Map();
const idCache = new Map();
for (const rel of REQUIRED_HTML_PAGES) {
const full = resolve(absRoot, rel);
if (!existsSync(full) || !statSync(full).isFile()) {
errors.push(`Missing required HTML page: ${rel}`);
continue;
}
const html = readFileSync(full, "utf8");
pageCache.set(full, html);
idCache.set(full, extractIds(html));
}
for (const rel of REQUIRED_HTML_PAGES) {
const full = resolve(absRoot, rel);
const html = pageCache.get(full);
if (html === undefined) continue;
pagesChecked++;
const csp = extractCspContent(html);
if (!csp) {
errors.push(`${rel}: missing Content-Security-Policy <meta> tag`);
} else {
if (!/default-src\s+[^;]*'self'/i.test(csp)) {
errors.push(`${rel}: CSP missing default-src 'self'`);
}
if (!/script-src\s+[^;]*'self'/i.test(csp)) {
errors.push(`${rel}: CSP missing script-src 'self'`);
}
if (!/object-src\s+[^;]*'none'/i.test(csp)) {
errors.push(`${rel}: CSP missing object-src 'none'`);
}
if (/'unsafe-eval'/i.test(csp)) {
errors.push(`${rel}: CSP must not allow 'unsafe-eval'`);
}
}
const pageDir = dirname(full);
for (const ref of extractLocalRefs(html)) {
linksChecked++;
const [rawPath, rawHash] = ref.split("#", 2);
let targetFile = full;
if (rawPath && rawPath.length > 0) {
const candidate = resolve(pageDir, rawPath);
if (!candidate.startsWith(absRoot)) {
errors.push(`${rel}: link escapes website root (${ref})`);
continue;
}
if (existsSync(candidate) && statSync(candidate).isDirectory()) {
targetFile = resolve(candidate, "index.html");
} else {
targetFile = candidate;
}
if (!existsSync(targetFile) || !statSync(targetFile).isFile()) {
errors.push(`${rel}: broken link target '${ref}'`);
continue;
}
}
if (rawHash && rawHash.length > 0) {
let ids = idCache.get(targetFile);
if (!ids && existsSync(targetFile) && statSync(targetFile).isFile()) {
const targetHtml = readFileSync(targetFile, "utf8");
ids = extractIds(targetHtml);
idCache.set(targetFile, ids);
}
if (!ids || !ids.has(rawHash)) {
errors.push(`${rel}: broken anchor '#${rawHash}' in '${ref}'`);
}
}
}
}
return {
ok: errors.length === 0,
pagesChecked,
linksChecked,
errors,
};
}
const isDirectRun =
process.argv[1] &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isDirectRun) {
const res = verifyWebsiteDirectory();
if (!res.ok) {
for (const err of res.errors) {
console.error(`Website verification error: ${err}`);
}
process.exit(1);
}
console.log(
`Verified ${res.pagesChecked} website HTML pages and ${res.linksChecked} internal links/assets.`,
);
}
+28 -2
View File
@@ -134,6 +134,7 @@ interface ParsedCliArgs {
readonly signManifest: boolean;
readonly manifestKey?: string;
readonly publicKey?: string;
readonly artifactPath?: string;
readonly llmDirectives: boolean;
readonly weaveDecoys: boolean;
readonly selfSeal: boolean;
@@ -149,6 +150,9 @@ interface ParsedCliArgs {
readonly allowJsWasmHydrateDump: boolean;
readonly allowWasmXorMaskSidecar: boolean;
readonly allowWasmSealXorKnownPlaintext: boolean;
readonly allowPlaintextString: boolean;
readonly allowSinglePointIntegrity: boolean;
readonly allowMissingBindRuntime: boolean;
readonly lang: NativeHeaderLanguage;
readonly clients: SupportedAgentClientId[];
readonly allDetected: boolean;
@@ -175,6 +179,7 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
let signManifest = false;
let manifestKey: string | undefined;
let publicKey: string | undefined;
let artifactPath: string | undefined;
let llmDirectives = false;
let weaveDecoys = false;
let selfSeal = false;
@@ -189,6 +194,9 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
let allowJsWasmHydrateDump = false;
let allowWasmXorMaskSidecar = false;
let allowWasmSealXorKnownPlaintext = false;
let allowPlaintextString = false;
let allowSinglePointIntegrity = false;
let allowMissingBindRuntime = false;
let allowPanelOfflineOracle = false;
let lang: NativeHeaderLanguage = "c";
const clients: SupportedAgentClientId[] = [];
@@ -231,6 +239,8 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
manifestKey = argv[++i]!;
} else if (arg === "--public-key" && i + 1 < argv.length) {
publicKey = argv[++i]!;
} else if (arg === "--artifact" && i + 1 < argv.length) {
artifactPath = argv[++i]!;
} else if (arg === "--llm-directives") {
llmDirectives = true;
} else if (arg === "--weave-decoys") {
@@ -259,6 +269,12 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
allowWasmXorMaskSidecar = true;
} else if (arg === "--allow-wasm-seal-xor-known-plaintext") {
allowWasmSealXorKnownPlaintext = true;
} else if (arg === "--allow-plaintext-string") {
allowPlaintextString = true;
} else if (arg === "--allow-single-point-integrity") {
allowSinglePointIntegrity = true;
} else if (arg === "--allow-missing-bind-runtime") {
allowMissingBindRuntime = true;
} else if (arg.startsWith("--wasm-preserve-exports=")) {
wasmPreserveExports = arg
.slice("--wasm-preserve-exports=".length)
@@ -333,6 +349,7 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
signManifest,
...(manifestKey !== undefined ? { manifestKey } : {}),
...(publicKey !== undefined ? { publicKey } : {}),
...(artifactPath !== undefined ? { artifactPath } : {}),
llmDirectives,
weaveDecoys,
selfSeal,
@@ -348,6 +365,9 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs {
allowJsWasmHydrateDump,
allowWasmXorMaskSidecar,
allowWasmSealXorKnownPlaintext,
allowPlaintextString,
allowSinglePointIntegrity,
allowMissingBindRuntime,
lang,
clients,
allDetected,
@@ -618,6 +638,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
allowJsWasmHydrateDump: parsed.allowJsWasmHydrateDump,
allowWasmXorMaskSidecar: parsed.allowWasmXorMaskSidecar,
allowWasmSealXorKnownPlaintext: parsed.allowWasmSealXorKnownPlaintext,
allowPlaintextString: parsed.allowPlaintextString,
allowSinglePointIntegrity: parsed.allowSinglePointIntegrity,
allowMissingBindRuntime: parsed.allowMissingBindRuntime,
allowLaneIndependentGates: parsed.allowLaneIndependentGates,
allowPanelOfflineOracle: parsed.allowPanelOfflineOracle,
allowStablePanelDeriveAbi: parsed.allowStablePanelDeriveAbi,
@@ -635,6 +658,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
wasmSealXor: report.details.wasmSealXor.length,
lanes: report.details.lanes.length,
panelDerive: report.details.panelDerive.length,
plaintextSecrets: report.details.plaintextSecrets.length,
integrityCoverage: report.details.integrityCoverage.length,
bindScope: report.details.bindScope.length,
} }, null, 2));
} else {
console.log(formatPackagingGatesReport(report));
@@ -966,10 +992,10 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
case "verify-manifest": {
const target = parsed.positionals[0];
if (!target) {
console.error("Error: Missing <manifest> path for `bla verify-manifest <manifest> [--public-key <pem>]`.");
console.error("Error: Missing <manifest> path for `bla verify-manifest <manifest> [--public-key <pem>] [--artifact <path>]`.");
return 1;
}
const result = verifyManifestFile(target, parsed.publicKey);
const result = verifyManifestFile(target, parsed.publicKey, parsed.artifactPath);
if (parsed.json) {
console.log(JSON.stringify(result, null, 2));
} else {
+6 -2
View File
@@ -22,6 +22,8 @@ export interface BlaProjectConfig {
readonly selfSeal?: boolean;
/** Opt-in sidecar/entry entanglement strip⇒fail for JS/Python (issue #40). Parity with CLI `--sidecar-entangle` / MCP `sidecar_entangle`. */
readonly sidecarEntangle?: boolean;
/** Enforce Agent-First Closed-Loop: refuse hardening if source files lack verified Stage 2 surgical weave. */
readonly requireAgentWeave?: boolean;
/** WASM export names that must remain the public ABI when export rename runs (issue #40.3). */
readonly wasmPreserveExports?: readonly string[];
/** When true, allow harden/defend of lane-independent JS gates (issue #40.1). Default false. */
@@ -82,6 +84,8 @@ const BOOLEAN_CONFIG_KEYS = [
"honeySourceMaps",
"weaveDecoys",
"selfSeal",
"sidecarEntangle",
"requireAgentWeave",
"allowLaneIndependentGates",
"allowPlaintextSeal",
"allowWasmClearParamCarriers",
@@ -262,7 +266,7 @@ export function resolveProjectSeed(
let targetPath: string;
if (loaded.sourcePath && !loaded.sourcePath.endsWith("package.json")) {
targetPath = loaded.sourcePath;
const existing = JSON.parse(readFileSync(targetPath, "utf8")) as BlaProjectConfig;
const existing = readConfigFile(targetPath);
persistSeed(targetPath, seed, existing);
} else {
targetPath = join(root, ".blarc");
@@ -280,7 +284,7 @@ export function initBlaConfig(
): { configPath: string; created: boolean; config: BlaProjectConfig } {
const configPath = join(resolve(targetDir), "bla.config.json");
if (existsSync(configPath) && !overwrite) {
const existing = JSON.parse(readFileSync(configPath, "utf8")) as BlaProjectConfig;
const existing = readConfigFile(configPath);
const merged = { ...DEFAULT_BLA_CONFIG, ...existing };
if (!isUsableSeed(merged.seed)) {
const seed = generateProjectSeed();
+4 -1
View File
@@ -216,7 +216,10 @@ export function detectArtifactFormat(targetPath: string): ArtifactFormat {
if ([".html", ".htm"].includes(ext)) return "html-bundle";
if ([".py", ".pyw"].includes(ext)) return "python-source";
if (ext === ".wasm") return "wasm";
if ([".sqlite", ".sqlite3", ".db"].includes(ext)) return "sqlite";
// Only unambiguous `.sqlite`/`.sqlite3` extensions fall back without magic so
// corrupt SQLite files still fail closed; generic `.db` files (JSON/hex state,
// LevelDB, etc.) require the `SQLite format 3\0` magic check at step 5 (#130).
if ([".sqlite", ".sqlite3"].includes(ext)) return "sqlite";
if (ext === ".gguf") return "model-gguf";
if (ext === ".dex") return "android-dex";
if ([".plist", ".entitlements", ".mobileprovision"].includes(ext)) return "apple-plist";
+131 -16
View File
@@ -1,15 +1,17 @@
import { createPublicKey } from "node:crypto";
import { readFileSync } from "node:fs";
import { createHash, createPublicKey } from "node:crypto";
import { existsSync, readFileSync, statSync } from "node:fs";
import { resolve } from "node:path";
import { verifyManifestSignature } from "./manifest-signing.js";
export interface ManifestVerifyResult {
/** Signature bytes are valid for the payload. */
/** Signature bytes (and artifact digest, when checked) are valid. */
readonly ok: boolean;
/** A signature object is present. */
readonly signed: boolean;
/** The caller supplied a trusted public key that matched the embedded key. */
readonly pinned: boolean;
/** True when the protected artifact file's SHA-256 was checked and matched `protectedSha256`. */
readonly artifactVerified: boolean;
readonly reason: string;
}
@@ -25,21 +27,39 @@ function normalizePublicKeyPem(pem: string): string {
* Without `publicKeyPath`, this only proves the manifest was signed by the key
* embedded in it (an attacker can re-sign their own edits). Supply
* `publicKeyPath` to pin the trusted key.
*
* When `artifactPath` is supplied — or when `<artifact>.bla-manifest.json` sits
* adjacent to a regular file `<artifact>` — `protectedSha256` in the manifest is
* also checked against the on-disk artifact bytes.
*/
export function verifyManifestFile(
manifestPath: string,
publicKeyPath?: string,
artifactPath?: string,
): ManifestVerifyResult {
const absManifest = resolve(manifestPath);
let manifest: Record<string, unknown>;
try {
const parsed: unknown = JSON.parse(readFileSync(resolve(manifestPath), "utf8"));
const parsed: unknown = JSON.parse(readFileSync(absManifest, "utf8"));
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
return { ok: false, signed: false, pinned: false, reason: "manifest must be a JSON object" };
return {
ok: false,
signed: false,
pinned: false,
artifactVerified: false,
reason: "manifest must be a JSON object",
};
}
manifest = parsed as Record<string, unknown>;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return { ok: false, signed: false, pinned: false, reason: `cannot read manifest: ${message}` };
return {
ok: false,
signed: false,
pinned: false,
artifactVerified: false,
reason: `cannot read manifest: ${message}`,
};
}
const rawSignature = manifest.signature;
@@ -49,14 +69,26 @@ export function verifyManifestFile(
typeof rawSignature === "object" &&
typeof (rawSignature as { value?: unknown }).value === "string";
if (!signed) {
return { ok: false, signed: false, pinned: false, reason: "manifest is unsigned" };
return {
ok: false,
signed: false,
pinned: false,
artifactVerified: false,
reason: "manifest is unsigned",
};
}
let pinned = false;
if (publicKeyPath !== undefined) {
const embedded = (rawSignature as { publicKey?: unknown }).publicKey;
if (typeof embedded !== "string") {
return { ok: false, signed: true, pinned: false, reason: "manifest signature has no public key" };
return {
ok: false,
signed: true,
pinned: false,
artifactVerified: false,
reason: "manifest signature has no public key",
};
}
try {
const expected = normalizePublicKeyPem(readFileSync(resolve(publicKeyPath), "utf8"));
@@ -67,24 +99,107 @@ export function verifyManifestFile(
ok: false,
signed: true,
pinned: true,
artifactVerified: false,
reason: "manifest public key does not match the pinned --public-key",
};
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return { ok: false, signed: true, pinned: false, reason: `cannot read pinned public key: ${message}` };
return {
ok: false,
signed: true,
pinned: false,
artifactVerified: false,
reason: `cannot read pinned public key: ${message}`,
};
}
}
const ok = verifyManifestSignature(manifest);
const sigOk = verifyManifestSignature(manifest);
if (!sigOk) {
return {
ok: false,
signed: true,
pinned,
artifactVerified: false,
reason: "signature invalid",
};
}
let resolvedArtifactPath: string | undefined;
if (artifactPath !== undefined) {
resolvedArtifactPath = resolve(artifactPath);
} else if (
absManifest.endsWith(".bla-manifest.json") &&
manifest.detectedFormat !== "directory"
) {
const adjacent = absManifest.slice(0, -".bla-manifest.json".length);
try {
if (existsSync(adjacent) && statSync(adjacent).isFile()) {
resolvedArtifactPath = adjacent;
}
} catch {
// Ignore inaccessible or non-file adjacent paths when not explicitly requested.
}
}
let artifactVerified = false;
if (resolvedArtifactPath !== undefined) {
const expectedSha = manifest.protectedSha256;
if (typeof expectedSha !== "string" || !/^[0-9a-f]{64}$/i.test(expectedSha)) {
return {
ok: false,
signed: true,
pinned,
artifactVerified: false,
reason: "manifest is missing a valid 64-hex protectedSha256 field for artifact verification",
};
}
try {
const st = statSync(resolvedArtifactPath);
if (!st.isFile()) {
return {
ok: false,
signed: true,
pinned,
artifactVerified: false,
reason: `cannot read artifact: ${resolvedArtifactPath} is not a regular file`,
};
}
const actualSha = createHash("sha256")
.update(readFileSync(resolvedArtifactPath))
.digest("hex");
if (actualSha !== expectedSha.toLowerCase()) {
return {
ok: false,
signed: true,
pinned,
artifactVerified: false,
reason: `artifact SHA-256 mismatch (expected ${expectedSha.toLowerCase()}, got ${actualSha})`,
};
}
artifactVerified = true;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return {
ok: false,
signed: true,
pinned,
artifactVerified: false,
reason: `cannot read artifact: ${message}`,
};
}
}
const keyNote = pinned
? "pinned key"
: "embedded key only — pass --public-key to authenticate";
const artifactNote = artifactVerified ? ", artifact SHA-256 verified" : "";
return {
ok,
ok: true,
signed: true,
pinned,
reason: ok
? pinned
? "signature valid (pinned key)"
: "signature valid (embedded key only — pass --public-key to authenticate)"
: "signature invalid",
artifactVerified,
reason: `signature valid (${keyNote}${artifactNote})`,
};
}
+1 -1
View File
@@ -11,7 +11,7 @@ function exists(path: string): boolean {
}
}
function physicalPath(path: string): string {
export function physicalPath(path: string): string {
const suffix: string[] = [];
let ancestor = path;
while (!exists(ancestor)) {
+154 -34
View File
@@ -10,6 +10,8 @@
* MCP: bla_encrypt_strings.
*/
import { parse } from "@babel/parser";
import _traverse from "@babel/traverse";
import { createHash } from "node:crypto";
import {
existsSync,
@@ -27,6 +29,13 @@ import {
lintPlaintextSecretsSource,
} from "./plaintext-secret-lint.js";
type UnwrapDefault<T> = T extends { readonly default: infer D } ? D : T;
type TraverseFn = UnwrapDefault<typeof _traverse>;
const traverse: TraverseFn =
typeof _traverse === "function"
? (_traverse as unknown as TraverseFn)
: (_traverse as unknown as { readonly default: TraverseFn }).default;
export const ENCRYPT_STRINGS_SCHEMA = "bla-encrypt-strings/v1" as const;
export interface EncryptStringsOptions {
@@ -213,30 +222,127 @@ function shouldEncrypt(lit: string, includeUrls: boolean): boolean {
return true;
}
function replaceLiteralsInJs(
source: string,
replacements: Map<string, string>,
): { readonly code: string; readonly count: number } {
let count = 0;
const keys = [...replacements.keys()].sort((a, b) => b.length - a.length);
let code = source;
for (const lit of keys) {
const call = replacements.get(lit)!;
const patterns = [
JSON.stringify(lit),
`'${lit.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`,
`"${lit.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`,
];
for (const p of patterns) {
if (!code.includes(p)) continue;
const parts = code.split(p);
if (parts.length > 1) {
count += parts.length - 1;
code = parts.join(call);
}
interface LiteralSpan {
readonly start: number;
readonly end: number;
readonly value: string;
}
function isNonReplaceableStringPosition(path: {
readonly node: unknown;
readonly parent: unknown;
readonly parentPath?: { readonly parent: unknown } | null;
}): boolean {
const node = path.node as Record<string, unknown>;
const parent = path.parent as Record<string, unknown> | null | undefined;
if (!parent) return false;
const pType = parent.type;
// Module specifiers in import / export declarations
if (
(pType === "ImportDeclaration" ||
pType === "ExportAllDeclaration" ||
pType === "ExportNamedDeclaration") &&
parent.source === node
) {
return true;
}
if (pType === "ImportAttribute") {
return true;
}
// TypeScript literal types or module references
if (
pType === "TSLiteralType" ||
pType === "TSExternalModuleReference" ||
pType === "TSImportType"
) {
return true;
}
// Non-computed object / class keys or destructuring pattern keys
if (
(pType === "ObjectProperty" ||
pType === "ObjectMethod" ||
pType === "ClassProperty" ||
pType === "ClassMethod" ||
pType === "TSPropertySignature" ||
pType === "TSMethodSignature") &&
parent.key === node &&
parent.computed !== true
) {
return true;
}
if (pType === "ObjectProperty" && path.parentPath?.parent) {
const grand = path.parentPath.parent as Record<string, unknown>;
if (grand.type === "ObjectPattern") return true;
}
// CommonJS require("...") or dynamic import("...")
if (pType === "CallExpression") {
const callee = parent.callee as Record<string, unknown> | undefined;
const args = parent.arguments as unknown[] | undefined;
if (
args?.[0] === node &&
(callee?.type === "Import" ||
(callee?.type === "Identifier" && callee.name === "require"))
) {
return true;
}
}
return { code, count };
return false;
}
function collectJsLiteralSpans(source: string): LiteralSpan[] {
try {
const ast = parse(source, {
sourceType: "unambiguous",
allowReturnOutsideFunction: true,
allowImportExportEverywhere: true,
allowSuperOutsideMethod: true,
plugins: ["typescript", "jsx", "decorators-legacy"],
});
const spans: LiteralSpan[] = [];
traverse(ast, {
StringLiteral(path) {
if (isNonReplaceableStringPosition(path)) return;
const { start, end, value } = path.node;
if (typeof start === "number" && typeof end === "number") {
spans.push({ start, end, value });
}
},
TemplateLiteral(path) {
if (
path.parent.type === "TaggedTemplateExpression" ||
path.node.expressions.length > 0 ||
path.node.quasis.length !== 1 ||
isNonReplaceableStringPosition(path)
) {
return;
}
const quasi = path.node.quasis[0];
const { start, end } = path.node;
const value = quasi?.value.cooked ?? quasi?.value.raw ?? "";
if (typeof start === "number" && typeof end === "number") {
spans.push({ start, end, value });
}
},
});
spans.sort((a, b) => a.start - b.start);
return spans;
} catch {
// Fallback for non-standard script fragments: match quote/backtick literals while skipping comments
const spans: LiteralSpan[] = [];
const tokenRe =
/\/\/[^\n]*|\/\*[\s\S]*?\*\/|'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\$]|\$(?!\{))*`/g;
let m: RegExpExecArray | null;
while ((m = tokenRe.exec(source)) !== null) {
const raw = m[0]!;
if (raw.startsWith("//") || raw.startsWith("/*")) continue;
const [decoded] = extractStringLiterals(raw);
if (decoded !== undefined) {
spans.push({ start: m.index, end: m.index + raw.length, value: decoded });
}
}
return spans;
}
}
function transformJsSource(
@@ -248,20 +354,28 @@ function transformJsSource(
readonly encrypted: string[];
readonly skipped: number;
} {
const literals = extractStringLiterals(source);
// Never re-encrypt a file that already carries the _blaS decrypt stub
if (source.includes("var _blaS=") && source.includes("var _blaT=")) {
return { code: source, encrypted: [], skipped: 0 };
}
const spans = collectJsLiteralSpans(source);
const replaceable: LiteralSpan[] = [];
const unique: string[] = [];
const seen = new Set<string>();
let skipped = 0;
for (const lit of literals) {
if (!shouldEncrypt(lit, includeUrls)) {
for (const span of spans) {
if (!shouldEncrypt(span.value, includeUrls)) {
skipped += 1;
continue;
}
if (seen.has(lit)) continue;
seen.add(lit);
unique.push(lit);
replaceable.push(span);
if (!seen.has(span.value)) {
seen.add(span.value);
unique.push(span.value);
}
}
if (unique.length === 0) {
if (unique.length === 0 || replaceable.length === 0) {
return { code: source, encrypted: [], skipped };
}
@@ -276,14 +390,20 @@ function transformJsSource(
const ksName = prng.identifier({ style: "camel", hint: "blaK", entropy: 3 });
const stub = buildRuntimeStub(table, keystream, fnName, tableName, ksName);
const replacements = new Map<string, string>();
const indexByLiteral = new Map<string, number>();
unique.forEach((lit, i) => {
replacements.set(lit, `${fnName}(${i})`);
indexByLiteral.set(lit, i);
});
const { code: body, count } = replaceLiteralsInJs(source, replacements);
if (count === 0) {
return { code: source, encrypted: [], skipped };
// Splice AST spans in reverse order so earlier offsets stay valid.
let body = source;
const descending = [...replaceable].sort((a, b) => b.start - a.start);
for (const span of descending) {
const idx = indexByLiteral.get(span.value);
if (idx === undefined) continue;
body = `${body.slice(0, span.start)}${fnName}(${idx})${body.slice(span.end)}`;
}
// Keep shebang / "use strict" at the very top so Node can still execute the file.
const shebangMatch = body.match(/^#![^\n]*\n/);
const shebang = shebangMatch ? shebangMatch[0] : "";
+43 -13
View File
@@ -5,8 +5,9 @@ import {
statSync,
writeFileSync,
} from "node:fs";
import { basename, dirname, join, relative, resolve, sep } from "node:path";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { detectArtifactFormat } from "../core/detector.js";
import { physicalPath } from "../core/output-path.js";
import { walkBounded } from "../core/walk.js";
import type { ArtifactFormat, ProtectionIntensity } from "../core/types.js";
import { BLA_IDENTITY } from "../identity.js";
@@ -336,6 +337,7 @@ function collectRootArtifacts(
projectRoot: string,
maxArtifacts: number,
skipDirs: ReadonlySet<string>,
excludeDir?: string,
): DiscoveredArtifact[] {
const formats = new Map<string, ArtifactFormat>();
const files = walkBounded(root, {
@@ -346,6 +348,9 @@ function collectRootArtifacts(
// Locale-independent name sort so offset paging is stable across platforms.
sortEntries: true,
accept: (full, name) => {
if (excludeDir && (full === excludeDir || full.startsWith(excludeDir + sep))) {
return false;
}
const format = detectArtifactFormat(full);
if (!isProtectableFormat(format)) return false;
// Skip already-shielded outputs to avoid re-hardening loops.
@@ -373,7 +378,7 @@ function collectRootArtifacts(
*/
export function discoverHardenableArtifacts(
directory: string = process.cwd(),
options: { readonly maxArtifacts?: number; readonly offset?: number } = {},
options: { readonly maxArtifacts?: number; readonly offset?: number; readonly outputDirectory?: string } = {},
): readonly DiscoveredArtifact[] {
return discoverHardenTargets(directory, options).artifacts;
}
@@ -387,13 +392,14 @@ export function discoverHardenableArtifacts(
*/
export function discoverHardenTargets(
directory: string = process.cwd(),
options: { readonly maxArtifacts?: number; readonly offset?: number } = {},
options: { readonly maxArtifacts?: number; readonly offset?: number; readonly outputDirectory?: string } = {},
): HardenDiscoveryResult {
const abs = resolve(directory);
const maxArtifacts = Math.max(1, Math.floor(options.maxArtifacts ?? MAX_DISCOVERED_ARTIFACTS));
const offset = Math.max(0, Math.floor(options.offset ?? 0));
const excludeDir = options.outputDirectory ? resolve(options.outputDirectory) : undefined;
// Collect one past the page end so truncated/nextOffset stay honest.
const all = collectHardenableArtifacts(abs, offset + maxArtifacts + 1);
const all = collectHardenableArtifacts(abs, offset + maxArtifacts + 1, excludeDir);
const page = all.slice(offset, offset + maxArtifacts);
const truncated = all.length > offset + maxArtifacts;
return {
@@ -409,6 +415,7 @@ export function discoverHardenTargets(
function collectHardenableArtifacts(
abs: string,
maxArtifacts: number,
excludeDir?: string,
): readonly DiscoveredArtifact[] {
if (!existsSync(abs)) {
throw new Error(`Path not found: ${abs}`);
@@ -430,11 +437,11 @@ function collectHardenableArtifacts(
for (const root of preferred) {
const remaining = maxArtifacts - found.length;
if (remaining <= 0) break;
found.push(...collectRootArtifacts(root, abs, remaining, SKIP_DIR_NAMES));
found.push(...collectRootArtifacts(root, abs, remaining, SKIP_DIR_NAMES, excludeDir));
}
if (includeProjectRootSupplemental && found.length < maxArtifacts) {
found.push(
...collectRootArtifacts(abs, abs, maxArtifacts - found.length, SUPPLEMENTAL_SKIP_DIR_NAMES),
...collectRootArtifacts(abs, abs, maxArtifacts - found.length, SUPPLEMENTAL_SKIP_DIR_NAMES, excludeDir),
);
}
// De-dupe by absolute path (cargo release may overlap target/)
@@ -473,8 +480,37 @@ export function hardenProject(
}
const maxArtifacts = options.maxArtifacts ?? MAX_DISCOVERED_ARTIFACTS;
const outputRoot = resolve(
options.outputDirectory ??
(existsSync(absDir) && statSync(absDir).isDirectory()
? join(absDir, ".bla-hardened")
: join(dirname(absDir), ".bla-hardened")),
);
if (options.outputDirectory) {
if (existsSync(absDir)) {
const physSrc = physicalPath(absDir);
const physOut = physicalPath(outputRoot);
if (physSrc === physOut) {
throw new Error(
"Output directory must not be the input directory; in-place project hardening is not supported.",
);
}
}
const relFromProject = relative(absDir, outputRoot);
const checkSegments =
!isAbsolute(relFromProject) && !relFromProject.startsWith("..")
? relFromProject.split(/[\\/]+/).filter(Boolean)
: [basename(outputRoot)];
for (const seg of checkSegments) {
if (seg === ".git" || seg === "node_modules" || seg === ".hg" || seg === ".svn") {
throw new Error(`Refusing to use protected directory as output: ${outputRoot}`);
}
}
}
const dryRun = options.dryRun === true;
const discovery = discoverHardenTargets(absDir, { maxArtifacts });
const discovery = discoverHardenTargets(absDir, { maxArtifacts, outputDirectory: outputRoot });
const discovered = discovery.artifacts;
const packagingBlocks = evaluateHardenProjectPackagingBlocks({
@@ -493,12 +529,6 @@ export function hardenProject(
const blockingJsHydrateDump = packagingBlocks.blockingJsHydrateDump;
const blockingWasmXorMask = packagingBlocks.blockingWasmXorMask;
const blockingWasmSealXor = packagingBlocks.blockingWasmSealXor;
const outputRoot = resolve(
options.outputDirectory ??
(statSync(absDir).isDirectory()
? join(absDir, ".bla-hardened")
: join(dirname(absDir), ".bla-hardened")),
);
let plannedOutputs = discovered.map((artifact) => {
const outputPath = planArtifactOutputPath(artifact, outputRoot);
return { artifact, outputPath, outputExisted: existsSync(outputPath) };
+42 -3
View File
@@ -8,6 +8,7 @@ import {
readFileSync,
readdirSync,
renameSync,
rmSync,
statSync,
unlinkSync,
writeFileSync,
@@ -963,16 +964,27 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
binarySectionsPatched = res.blocksInjected;
counteredVectors.add("uf2-firmware-inspection");
} else if (format === "directory") {
const outputExistedBefore = existsSync(absOutput);
mkdirSync(absOutput, { recursive: true });
const walkAndProtect = (srcDir: string, dstDir: string): void => {
mkdirSync(dstDir, { recursive: true });
for (const entry of readdirSync(srcDir, { withFileTypes: true })) {
if (entry.name === "node_modules" || entry.name === ".git") continue;
if (
entry.name === "node_modules" ||
entry.name === ".git" ||
entry.name === ".hg" ||
entry.name === ".svn" ||
entry.name === ".bla-hardened" ||
entry.name === "__pycache__"
) {
continue;
}
if (entry.isSymbolicLink()) continue;
const srcFull = join(srcDir, entry.name);
const dstFull = join(dstDir, entry.name);
if (entry.isDirectory()) {
walkAndProtect(srcFull, dstFull);
} else {
} else if (entry.isFile()) {
const ext = extname(entry.name).toLowerCase();
if ([".js", ".ts", ".mjs", ".cjs", ".jsx", ".tsx"].includes(ext)) {
const raw = readFileSync(srcFull, "utf8");
@@ -980,6 +992,7 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
intensity,
seed: `${seed}:${entry.name}`,
filename: entry.name,
llmDirectives: options.llmDirectives,
...(selfSealTransformOption(options, absOutput) !== undefined ? { selfSeal: selfSealTransformOption(options, absOutput)! } : {}),
});
const honey = generateHoneySourceMap(
@@ -1007,6 +1020,21 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
intensity,
seed: `${seed}:${entry.name}`,
honeySourceMaps: options.honeySourceMaps,
llmDirectives: options.llmDirectives,
weaveDecoys: options.weaveDecoys,
selfSeal: options.selfSeal,
sidecarEntangle: options.sidecarEntangle,
wasmPreserveExports: options.wasmPreserveExports,
allowLaneIndependentGates: options.allowLaneIndependentGates,
allowPlaintextSeal: options.allowPlaintextSeal,
allowWasmClearParamCarriers: options.allowWasmClearParamCarriers,
allowStablePanelDeriveAbi: options.allowStablePanelDeriveAbi,
allowJsAesUnwrap: options.allowJsAesUnwrap,
allowPanelOfflineOracle: options.allowPanelOfflineOracle,
allowJsWasmHydrateDump: options.allowJsWasmHydrateDump,
allowWasmXorMaskSidecar: options.allowWasmXorMaskSidecar,
allowWasmSealXorKnownPlaintext: options.allowWasmSealXorKnownPlaintext,
selfSealSiblingPaths: options.selfSealSiblingPaths,
});
decoyFunctionsInjected += subRes.metrics.decoyFunctionsInjected;
fakeCrossReferencesCreated += subRes.metrics.fakeCrossReferencesCreated;
@@ -1030,7 +1058,18 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult {
}
}
};
walkAndProtect(absInput, absOutput);
try {
walkAndProtect(absInput, absOutput);
} catch (err) {
if (!outputExistedBefore) {
try {
rmSync(absOutput, { recursive: true, force: true });
} catch {
// Preserve the original child protection failure if cleanup fails.
}
}
throw err;
}
counteredVectors.add("js-static-semantics");
counteredVectors.add("electron-ipc-bridge");
counteredVectors.add("js-route-rpc-inventory");
+14
View File
@@ -834,6 +834,14 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
type: "boolean",
description: "Treat cleartext sensitive literals as non-blocking (lab only)",
},
allow_single_point_integrity: {
type: "boolean",
description: "Treat single-point integrity coverage as non-blocking (lab only)",
},
allow_missing_bind_runtime: {
type: "boolean",
description: "Treat missing/narrow bind runtime scope as non-blocking (lab only)",
},
},
additionalProperties: false,
},
@@ -1526,6 +1534,12 @@ function runPackagingGatesLint(args: Record<string, unknown>): PackagingGatesRep
...(args.allow_plaintext_string === true
? { allowPlaintextString: true }
: {}),
...(args.allow_single_point_integrity === true
? { allowSinglePointIntegrity: true }
: {}),
...(args.allow_missing_bind_runtime === true
? { allowMissingBindRuntime: true }
: {}),
});
}
+15 -4
View File
@@ -233,11 +233,22 @@ function snapshotBusinessTables(
const digests: BusinessTableDigest[] = [];
for (const { name } of tables) {
if (isHoneyTableName(name)) continue;
const rows = db
.prepare(`SELECT * FROM ${quoteIdentifier(name)} ORDER BY rowid`)
.all();
let rows: unknown[];
try {
rows = db
.prepare(`SELECT * FROM ${quoteIdentifier(name)} ORDER BY rowid`)
.all();
} catch {
rows = db
.prepare(`SELECT * FROM ${quoteIdentifier(name)}`)
.all();
}
const hash = createHash("sha256")
.update(JSON.stringify(rows))
.update(
JSON.stringify(rows, (_k, v) =>
typeof v === "bigint" ? v.toString() : v,
),
)
.digest("hex");
digests.push({
name,
+5
View File
@@ -1441,6 +1441,11 @@ function walkWeaveCandidateFiles(
if (/\.shielded(\.|$)/i.test(ent.name)) continue;
const ext = extname(ent.name).toLowerCase();
if (INTERESTING_EXT.has(ext) || ent.name === "global-metadata.dat") {
// Generic `.db` files may be non-SQLite runtime state (#130); only include
// them as weave candidates when format detection recognizes them.
if (ext === ".db" && detectArtifactFormat(full) === "unknown") {
continue;
}
out.push(full);
}
}
+17 -2
View File
@@ -2,7 +2,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { loadBlaConfig } from "../src/core/config.js";
import { initBlaConfig, loadBlaConfig, resolveProjectSeed } from "../src/core/config.js";
const tempDirs: string[] = [];
function createTempDir(): string {
@@ -43,10 +43,25 @@ describe(".blarc/config validation", () => {
expect(() => loadBlaConfig(dir)).toThrow(/intensity.*stealth, balanced, maximum, bankrupt/);
});
it("fails loudly on a non-boolean boolean field", () => {
it("fails loudly on a non-boolean boolean field including sidecarEntangle and requireAgentWeave", () => {
const dir = createTempDir();
writeFileSync(join(dir, ".blarc"), JSON.stringify({ selfSeal: "yes" }), "utf8");
expect(() => loadBlaConfig(dir)).toThrow(/selfSeal.*boolean/);
writeFileSync(join(dir, ".blarc"), JSON.stringify({ sidecarEntangle: 1 }), "utf8");
expect(() => loadBlaConfig(dir)).toThrow(/sidecarEntangle.*boolean/);
writeFileSync(join(dir, ".blarc"), JSON.stringify({ requireAgentWeave: "true" }), "utf8");
expect(() => loadBlaConfig(dir)).toThrow(/requireAgentWeave.*boolean/);
});
it("validates existing config when resolveProjectSeed or initBlaConfig runs", () => {
const dir = createTempDir();
writeFileSync(join(dir, ".blarc"), "{ malformed", "utf8");
expect(() => resolveProjectSeed(dir)).toThrow(/Invalid BLA config at .*\.blarc/);
writeFileSync(join(dir, "bla.config.json"), "{ malformed", "utf8");
expect(() => initBlaConfig(dir)).toThrow(/Invalid BLA config at .*bla\.config\.json/);
});
it("rejects config files above the size cap", () => {
+6
View File
@@ -25,15 +25,21 @@ describe("core domain modules previously without dedicated tests", () => {
const py = path.join(dir, "app.py");
const wasm = path.join(dir, "core.wasm");
const sqlite = path.join(dir, "db.sqlite");
const sqliteDb = path.join(dir, "db-with-magic.db");
const opaqueDb = path.join(dir, "runtime-output.db");
const missing = path.join(dir, "nope.xyz");
fs.writeFileSync(py, "x = 1\n", "utf8");
fs.writeFileSync(wasm, Buffer.from([0x00, 0x61, 0x73, 0x6d]), "utf8");
fs.writeFileSync(sqlite, Buffer.from("SQLite format 3\0"), "utf8");
fs.writeFileSync(sqliteDb, Buffer.from("SQLite format 3\0"), "utf8");
fs.writeFileSync(opaqueDb, "not a database\n", "utf8");
fs.mkdirSync(path.join(dir, "sub"));
expect(detectArtifactFormat(py)).toBe("python-source");
expect(detectArtifactFormat(wasm)).toBe("wasm");
expect(detectArtifactFormat(sqlite)).toBe("sqlite");
expect(detectArtifactFormat(sqliteDb)).toBe("sqlite");
expect(detectArtifactFormat(opaqueDb)).toBe("unknown");
expect(detectArtifactFormat(missing)).toBe("unknown");
expect(detectArtifactFormat(path.join(dir, "sub"))).toBe("directory");
});
+53 -3
View File
@@ -1,8 +1,11 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { protectTarget } from "../src/engine/protector.js";
import { buildWeavePlan } from "../src/shields/weave/weave-decoy.js";
import { isNodeSqliteAvailable, getDatabaseSyncClass } from "../src/core/sqlite-runtime.js";
import { protectSqliteBuffer } from "../src/shields/formats/sqlite.js";
const tempDirs: string[] = [];
function createTempDir(): string {
@@ -18,9 +21,10 @@ afterEach(() => {
});
describe("directory protection reports child failures instead of copying unprotected bytes", () => {
it("fails loudly when a detected child artifact cannot be protected", () => {
it("fails loudly when a detected child artifact cannot be protected and cleans up partial output directory", () => {
const dir = createTempDir();
const input = join(dir, "in");
const output = join(dir, "out");
mkdirSync(input, { recursive: true });
writeFileSync(join(input, "app.js"), "const x = 1;\n", "utf8");
// Invalid WASM magic bytes: format detection routes this to the WASM shield,
@@ -31,10 +35,11 @@ describe("directory protection reports child failures instead of copying unprote
expect(() =>
protectTarget({
inputPath: input,
outputPath: join(dir, "out"),
outputPath: output,
intensity: "balanced",
}),
).toThrow(/Directory protection failed for 'broken\.wasm'/);
expect(existsSync(output)).toBe(false);
});
it("still copies non-protectable file types as a documented pass-through", () => {
@@ -54,4 +59,49 @@ describe("directory protection reports child failures instead of copying unprote
expect(result.detectedFormat).toBe("directory");
expect(readFileSync(join(output, "notes.txt"), "utf8")).toBe("plain text asset");
});
it("copies .db files without the SQLite magic instead of aborting the directory", () => {
const dir = createTempDir();
const input = join(dir, "in");
const output = join(dir, "out");
mkdirSync(input, { recursive: true });
writeFileSync(join(input, "app.js"), "const x = 1;\n", "utf8");
writeFileSync(join(input, "runtime-output.db"), "hex-encoded json\n", "utf8");
const result = protectTarget({
inputPath: input,
outputPath: output,
intensity: "balanced",
});
expect(result.detectedFormat).toBe("directory");
expect(readFileSync(join(output, "runtime-output.db"), "utf8")).toBe("hex-encoded json\n");
// Weave planner also ignores non-SQLite .db files so overallStatus is not downgraded
const plan = buildWeavePlan(input);
expect(plan.targets.map((t) => t.relativePath)).toEqual(["app.js"]);
expect(plan.overallStatus).toBe("ready");
});
it("protects SQLite databases containing WITHOUT ROWID tables", () => {
if (!isNodeSqliteAvailable()) return;
const dir = createTempDir();
const dbPath = join(dir, "without-rowid.db");
const DatabaseSync = getDatabaseSyncClass();
const db = new DatabaseSync(dbPath);
db.exec(`
PRAGMA journal_mode = DELETE;
CREATE TABLE kv_store (
k TEXT PRIMARY KEY,
v TEXT NOT NULL
) WITHOUT ROWID;
INSERT INTO kv_store (k, v) VALUES ('tier', 'pro');
`);
db.close();
const raw = readFileSync(dbPath);
const res = protectSqliteBuffer(raw, { intensity: "balanced", seed: "without-rowid-seed" });
expect(res.honeyTablesInjected).toBeGreaterThanOrEqual(5);
expect(res.businessDataState).toBe("business-data-preserved");
});
});
+39
View File
@@ -115,4 +115,43 @@ module.exports = { unlock };
expect(report.status).toBe("noop");
expect(report.totalEncrypted).toBe(0);
});
it("uses AST spans so comments and object keys are preserved while backtick templates are encrypted", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-enc-ast-"));
const secret = "FLAG{ast_span_safe_secret_value_012345}";
const tmplSecret = "FLAG{template_literal_secret_67890}";
const src = [
`// Comment mentioning "${secret}" must not be rewritten into invalid JS`,
`const map = { "${secret}": "preserve-key-only" };`,
`const val = "${secret}";`,
`const tmpl = \`${tmplSecret}\`;`,
`module.exports = { map, val, tmpl };`,
].join("\n");
writeFileSync(join(dir, "license.cjs"), src, "utf8");
const report = encryptStrings({
path: dir,
seed: "ast-seed",
outDir: join(dir, "out"),
});
expect(report.status).toBe("ok");
expect(report.totalEncrypted).toBe(2);
const out = readFileSync(join(dir, "out", "license.cjs"), "utf8");
expect(out).toContain(`// Comment mentioning "${secret}"`);
expect(out).toContain(`"${secret}": "preserve-key-only"`);
expect(out).not.toContain(`\`${tmplSecret}\``);
const mod = require(join(dir, "out", "license.cjs"));
expect(mod.val).toBe(secret);
expect(mod.tmpl).toBe(tmplSecret);
// Re-running on an already encrypted output is idempotent (noop)
const second = encryptStrings({
path: join(dir, "out"),
seed: "ast-seed",
outDir: join(dir, "out2"),
});
expect(second.status).toBe("noop");
});
});
+23
View File
@@ -11,6 +11,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { protectTarget } from "../src/engine/protector.js";
import { hardenProject } from "../src/engine/harden.js";
const tempDirs: string[] = [];
@@ -109,4 +110,26 @@ describe("protectTarget output path safety", () => {
});
expect(readFileSync(inputFile, "utf8")).not.toBe(original);
});
it("excludes custom outputDirectory from hardenProject discovery and rejects project root or .git/.node_modules outputDirectory", () => {
const root = makeTempDir();
mkdirSync(join(root, "dist"), { recursive: true });
writeFileSync(join(root, "dist", "app.js"), "export const x = 1;\n", "utf8");
expect(() =>
hardenProject({ directory: root, outputDirectory: root }),
).toThrow(/Output directory must not be the input directory/);
expect(() =>
hardenProject({ directory: root, outputDirectory: join(root, ".git", "out") }),
).toThrow(/Refusing to use protected directory as output/);
const customOut = join(root, "custom-hardened");
const first = hardenProject({ directory: root, outputDirectory: customOut });
expect(first.hardenedCount).toBe(1);
// Re-running with the same custom outputDirectory must not re-discover custom-hardened/*
const second = hardenProject({ directory: root, outputDirectory: customOut });
expect(second.hardenedCount).toBe(1);
});
});
+37
View File
@@ -84,4 +84,41 @@ describe("bla verify-manifest", () => {
writeFileSync(manifestPath, JSON.stringify({ a: 1 }), "utf8");
await expect(runCli(["verify-manifest", manifestPath, "--json"])).resolves.toBe(2);
});
it("verifies adjacent file artifact SHA-256 and detects post-sign artifact tampering", async () => {
const dir = createTempDir();
const pair = generateManifestSigningKeyPair();
const artifactPath = join(dir, "bundle.shielded.js");
const manifestPath = `${artifactPath}.bla-manifest.json`;
const publicKeyPath = join(dir, "public.pem");
const content = "const x = 42;\n";
writeFileSync(artifactPath, content, "utf8");
const { createHash } = await import("node:crypto");
const sha = createHash("sha256").update(content).digest("hex");
const signed = signManifestPayload(
{
schema: "https://bla.tools/schemas/defense-manifest-v1.json",
blaVersion: "3.1.0",
protectedSha256: sha,
},
pair.privateKeyPem,
);
writeFileSync(manifestPath, JSON.stringify(signed, null, 2), "utf8");
writeFileSync(publicKeyPath, pair.publicKeyPem, "utf8");
const okRes = verifyManifestFile(manifestPath, publicKeyPath);
expect(okRes).toMatchObject({
ok: true,
signed: true,
pinned: true,
artifactVerified: true,
});
// Tamper with the artifact without changing the signed manifest
writeFileSync(artifactPath, "const x = 999;\n", "utf8");
const badRes = verifyManifestFile(manifestPath, publicKeyPath);
expect(badRes.ok).toBe(false);
expect(badRes.artifactVerified).toBe(false);
expect(badRes.reason).toMatch(/artifact SHA-256 mismatch/);
});
});
+42
View File
@@ -0,0 +1,42 @@
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { verifyWebsiteDirectory } from "../scripts/verify-website.mjs";
const tempDirs: string[] = [];
function createTempDir(): string {
const dir = mkdtempSync(join(tmpdir(), "bla-website-verify-"));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("website static verification", () => {
it("passes on the repository website directory", () => {
const res = verifyWebsiteDirectory();
expect(res.ok).toBe(true);
expect(res.errors).toEqual([]);
expect(res.pagesChecked).toBe(7);
expect(res.linksChecked).toBeGreaterThan(50);
});
it("flags missing CSP or broken internal links", () => {
const dir = createTempDir();
mkdirSync(join(dir, "assets"), { recursive: true });
writeFileSync(
join(dir, "index.html"),
"<!doctype html><html><head></head><body><a href=\"missing.html\">x</a></body></html>",
"utf8",
);
const res = verifyWebsiteDirectory(dir);
expect(res.ok).toBe(false);
expect(res.errors.some((e) => e.includes("missing Content-Security-Policy"))).toBe(true);
expect(res.errors.some((e) => e.includes("broken link target 'missing.html'"))).toBe(true);
});
});