@blamejs/core 0.15.10 → 0.15.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.15.x
10
10
 
11
+ - v0.15.11 (2026-06-14) — **Replaces a family of quadratic-time regexes that hostile input could use to stall a worker with linear scans, refuses a relocatable sealed-cell downgrade on the read side, fails closed when enabling row-level security behind a non-native driver, and scans the vendored crypto for known CVEs on every build.** Several text-handling primitives stripped trailing whitespace or extracted a mail address with a regex whose backtracking is quadratic in the input length on adversarial strings — a request body, a YAML document, a CSV cell, or a From header crafted as a long run of spaces could pin a worker's CPU. Each is now a linear character scan with identical output. The HTML-content check the MCP tool surface applies gained the vbscript: and data:text/html vectors it was missing. On the data-at-rest side, an AAD-bound (or per-row-key) column now refuses a plain, unbound vault cell on read — a relocatable envelope an attacker with write access could copy in from another row defeats the cross-row binding, so the field is nulled rather than surfaced; operators mid-migration opt back in with registerTable({ allowPlainMigration: true }). declareRowPolicy now treats row-level-security as enabled only on a value that unambiguously means true, so a non-native Postgres driver that returns the string "f" can no longer be read as "already on" and silently skip the ENABLE that protects the table's rows. Finally, because the framework's crypto is vendored rather than installed, npm audit and Dependabot never see it: every build now matches the vendored versions against the OSV vulnerability database, with a complementary Semgrep pass and workflow-file static analysis alongside. **Added:** *b.safeBuffer.indexAfterOpenTag(html, tagName)* — A linear helper that returns the offset just past a `<tag ...>` opening tag (case-insensitive), or -1 when absent or unterminated — the insertion point a response rewriter uses to splice content after <body> or <head> without a regex. It replaces the O(n^2) html.match(/<body[^>]*>/i) shape and is stricter than it: a real tag boundary is required after the name, so <bodyfoo> is not mistaken for <body>. **Security:** *Linear-time replacements across a family of quadratic regexes (ReDoS class)* — Several primitives located or stripped text with a regex whose backtracking is quadratic in V8 on adversarial input (CWE-1333): b.safeBuffer and the safe-env / safe-yaml / guard-csv parsers stripped trailing horizontal whitespace with /[ \t]+$/; b.mail extracted the address from a `Name <addr>` header with /<([^>]+)>/; the bot-disclosure and speculation-rules response middleware found the <body> insertion point with /<body[^>]*>/i; and the BIMI certificate-chain splitter walked PEM blocks with a lazy /BEGIN[\s\S]*?END/ scan. A crafted field — a long run of spaces, an unterminated bracket, a body carrying many <body starts with no closing >, a chain of BEGIN markers — could drive a worker's CPU to seconds of work. Each is now a linear scan: a shared b.safeBuffer.stripTrailingHspace (backward char walk), b.safeBuffer.indexAfterOpenTag (forward indexOf walk for the tag insertion point), a forward indexOf for address extraction, and an indexOf walk for the PEM split. Output is byte-identical (the tag-find is stricter — it no longer mistakes <bodyfoo> for <body>), and 400K-character adversarial inputs that took 8–85 seconds now complete in under 2 ms. · *MCP HTML-content check covers vbscript: and data:text/html* — The dangerous-markup check applied to text/html tool content matched <script>/<iframe>/<object>/<embed> and javascript: URLs but not the vbscript: scheme or data:text/html payloads. Both are now refused; data: URLs carrying non-HTML media (data:image/png and similar) are unaffected. · *AAD-bound columns refuse a plain sealed cell on read* — b.cryptoField.unsealRow now refuses a plain, unbound vault: envelope found on an AAD-bound (or per-row-key) column and nulls the field instead of returning it. A plain envelope carries no per-cell binding, so a writer who could place one — copied from anywhere under the same vault root — would otherwise relocate a value across rows or columns and defeat the copy-protection the AAD binding advertises. Operators migrating pre-AAD rows up to bound ciphertext opt into a bounded acceptance window with registerTable({ allowPlainMigration: true }) and clear it when migration completes. · *Row-level-security enablement fails closed on non-native drivers* — b.db.declareRowPolicy read pg_class.relrowsecurity to skip a redundant ENABLE ROW LEVEL SECURITY, but tested it with a bare truthiness check. A native pg driver returns a JS boolean; a proxy or ORM may return the string "f" for a disabled table — and "f" is truthy, so the check read it as already-enabled and silently skipped the ENABLE, leaving every row in the table unprotected while the migration reported success. RLS now counts as enabled only on a value that unambiguously means true (true, 1, or "t"/"true"/"1"/"on"/"yes"); every other shape re-issues ENABLE, a harmless no-op on an already-enabled table. · *Vendored-crypto CVE scanning, complementary SAST, and workflow static analysis in CI* — The framework ships zero npm runtime dependencies — its crypto (the noble suite, the WebAuthn server, the PKI layer) is vendored under lib/vendor/, where npm audit, Dependabot, and Socket cannot see it. Every build now generates a CycloneDX SBOM of the vendored tree (each library carrying an npm purl) and runs it through OSV-Scanner, matching the exact pinned version against the OSV vulnerability database; a published CVE or GHSA affecting a vendored version fails the build so the copy is refreshed before merge. A Semgrep pass (registry security-audit + javascript packs at ERROR severity) runs alongside CodeQL as complementary SAST, and actionlint statically checks the workflow files. All three install the OSS tool from its upstream release, matching the existing secret-scan gate's posture. **Detectors:** *Quadratic trailing-whitespace and tag-find regex detectors* — Two codebase-pattern detectors refuse reintroduction of the quadratic shapes: the /[ \t]+$/ trailing-whitespace strip (as .replace, .test, or via the named TRAILING_HSPACE_RE export) outside the linear helper that owns it, and the str.match(/<tag[^>]*>/) document-tag find that the response middleware must route through b.safeBuffer.indexAfterOpenTag. Each is proven to fire on the removed shape and stay silent on the linear replacement, so the ReDoS class cannot creep back into a new parser, guard, or response rewriter.
12
+
11
13
  - v0.15.10 (2026-06-13) — **Makes S3 Object-Lock version erasure reachable through the object store, and pins the build toolchain's native binary to a reviewed hash.** The object store gains the versioned-delete surface its S3 Object Lock support always needed for real erasure. An unversioned delete on a versioning-enabled (Object-Lock) bucket only writes a delete-marker — the data version survives — so the framework's own delete could report success while a record protected for compliance, or one a data subject asked to erase, stayed on disk. b.objectStore / b.storage now carry a versionId: put and saveRaw return the version they created, deleteFile(key, { versionId, bypassGovernanceRetention }) targets a specific version (refused — not silently delete-markered — when it is under an active retention), and listVersions enumerates versions and delete-markers so an erasure workflow can find them. Backends with no version surface (the filesystem backend, and the current Azure and GCS adapters) refuse a versioned delete loudly rather than silently dropping the current object. Separately, the build toolchain's native bundler binary is now verified against a reviewed SHA-256 pin so a tampered or drifted binary is caught before it bundles the framework. **Added:** *Versioned object delete + listVersions for S3 Object-Lock erasure* — b.storage.deleteFile and the b.objectStore sigv4 backend now accept opts.versionId to erase a specific object version, and opts.bypassGovernanceRetention to lift a GOVERNANCE-mode retention for callers with the permission (COMPLIANCE stays immutable to everyone). b.storage.saveRaw and the backend put now return the versionId they created on a versioning-enabled bucket, and a new b.storage.listVersions(prefix) / backend listVersions enumerates every version and delete-marker (key, versionId, isLatest, deleteMarker, size, lastModified, etag) so a right-to-erasure or crypto-shred workflow can target prior versions. On a backend with no version surface, listVersions throws VERSIONS_UNSUPPORTED and a versioned delete throws VERSIONID_UNSUPPORTED rather than silently acting on the current object. · *b.localDb.thin reaches SQLite resource-limit parity (limits option)* — b.localDb.thin now opens its node:sqlite handle with the same parse-time statement-size cap as b.db and the CLI — a SQL statement over 1 MiB is rejected at parse time, the SQLITE_LIMIT_LENGTH floor that guards prepare()/exec() of raw SQL against an attacker-influenced megaquery (SQLite's default is 1 GB). The cap is on by default; a new limits option (e.g. { sqlLength: 2 * 1024 * 1024 } or other SQLITE_LIMIT_* keys) lets an operator raise or extend it. Previously the thin opener had no limits plumbing, so a consumer on that path could not reach parity with the rest of the framework's SQLite surface. **Fixed:** *S3 Object-Lock version erasure is reachable through the framework delete path* — On a versioning-enabled (Object-Lock) bucket, an unversioned DELETE only writes a delete-marker — the protected data version survives untouched — yet the framework's delete had no versionId surface, so it issued the unversioned form and reported success while the bytes the lock protects remained. A retention or legal hold could therefore look enforced to the framework caller while the operation WORM actually blocks was unreachable. The delete path now targets the exact version: deleting a version under a COMPLIANCE retention is refused (it throws, even with bypassGovernanceRetention), a no-retention version erases cleanly, and the enforcement is proven end-to-end against MinIO through the framework's own API. · *b.configDrift.verifyVendorIntegrity is now working-directory-independent* — The vendored-dependency integrity check resolved each manifest file path against process.cwd(), so it only worked when run from the application root. Run from anywhere else it read-failed every entry (reporting ok:false), and under a crafted working directory that happened to contain a clean vendor tree it could hash a different tree than the one actually loaded. It now resolves each file under the framework's own vendor directory by default — the tree loaded at runtime — and honors an explicit libVendorDir for verifying a deployed tree elsewhere, so the result no longer depends on where the process was started. **Security:** *Build toolchain native binary pinned to a reviewed hash* — The native bundler binary the build toolchain runs (esbuild's per-platform compiler, a development dependency that never ships in the runtime) is now verified against a SHA-256 pin captured by diffing the published package tarballs and hashing the binary. The build gate fails if the on-disk binary does not match the reviewed hash for its (version, platform); for a version that has not been reviewed it notes the gap and skips rather than trusting an unverified binary. A cross-artifact check keeps the version in agreement across package.json, the CI install step, and the hash map, so the gate can never quietly test a version that was never diffed — closing a real drift where CI had been installing an older patch than package.json declared. The reviewed diff is benign: version strings plus an installer size-bound and error-message hardening, no new install hooks, files, or network paths, and no runtime-dependency impact. **Detectors:** *Object-store erasure guard, esbuild-pin agreement, + structural re-anchoring of the lint detectors* — A new guard locks the object-store delete path to the versioned-erasure contract: b.storage.deleteFile must thread versionId to the backend, so it can never silently revert to the WORM-blind unversioned delete. A second guard enforces that the esbuild build-tool version agrees across package.json, the CI install step, and the binary-hash map, so a future bump can't update one and leave the gate testing an unreviewed version. Separately, the framework's internal codebase-pattern lint detectors were re-anchored from fixed character spans to structural code boundaries, so they keep matching the code they guard as those functions grow rather than aging out of range; reviving them surfaced a few internal validation and transaction sites that now route through shared helpers (a required positive-integer-with-range validator and an async transaction wrapper) instead of hand-rolling the check. No public API change.
12
14
 
13
15
  - v0.15.9 (2026-06-13) — **Raises the Node floor to 24.16, adds SQLite parse-time resource caps, retries Windows rename locks on every atomic write and download, and ships a one-call secure logout that wipes client-side state.** This release moves the engines floor to the current Node 24 LTS patch level and adds three hardening primitives. node:sqlite handles now construct with SQLITE_LIMIT_* caps: a statement over 1 MiB is rejected at parse time (a DoS floor on the raw-SQL surface, complementary to the existing row-count gate) and ATTACH DATABASE is denied. Every final temp-to-destination rename — the file written by an atomic write, a downloaded file, a sealed vault key, a rotated log, an extracted archive entry — now routes through a single retry that rides out a transient Windows lock (antivirus, the search indexer, or a file-sync client briefly holding the destination), instead of surfacing the lock as a hard failure; the retry, previously hand-rolled and unreachable, is now the reusable b.atomicFile.renameWithRetry. And b.session.logout destroys a session and tells the browser to wipe its client-side state in one call: it emits an RFC 9527 Clear-Site-Data header and expires the session cookie before destroying the row, the secure-default logout that previously had to be assembled by hand. **Added:** *b.session.logout — one-call secure logout* — `b.session.logout(res, token, opts?)` destroys the server-side session AND tells the browser to wipe its client-side state in one call: it emits an RFC 9527 Clear-Site-Data response header (cookies + storage + cache + execution contexts by default) and expires the session cookie, then destroys the session row. `b.session.destroy` alone is a store operation with no response object, so it could not wipe the browser's cached pages, storage, or a stale tab still holding the now-revoked cookie — that wiring previously had to be mounted by hand. Pass `cookieName` to match a non-default cookie and `types` to choose the Clear-Site-Data directives. **Changed:** *Node engines floor raised to >=24.16.0* — The minimum supported Node is now 24.16.0 (the current Node 24 LTS patch level), up from 24.14.1. This is an LTS-currency bump — there are no Node CVE fixes between 24.14.1 and 24.16.0 (24.14.1 already carried the CVE-2026-21713 HMAC fix); it keeps the framework on the latest patched LTS and makes the node:sqlite resource-cap hardening below available everywhere. Pre-1.0, operators upgrade across the floor; Node 26 continues to satisfy it. **Fixed:** *b.watcher canonicalizes its root on Windows* — `b.watcher.create` now resolves its `root` to the real long path before watching. On Windows a root with an 8.3 short-name component (the system temp directory commonly resolves to one) made the native recursive backend deliver long-name event paths that no longer prefix-matched the watched root, which could abort the process under a strict libuv fs-event assertion. The watcher now canonicalizes the root (expanding short names and resolving symlinks), so events match the watched directory on Windows. **Security:** *SQLite parse-time statement-size cap* — Every node:sqlite database the framework opens — the main db handle and the CLI's handle — now constructs with a SQLITE_LIMIT_LENGTH cap: a SQL statement over 1 MiB is rejected at parse time. Because the query builder parameterizes every value, the size cap guards the raw-SQL surface (`b.db.runSql`) against an attacker-influenced megaquery the parser would otherwise process (SQLite's default is 1 GB); it is a parse-time DoS floor complementary to the existing row-count gate. Legitimate framework and operator statements are far under the cap. · *Windows rename-lock retry on every atomic rename and download* — On Windows a freshly-written file's destination is briefly held by antivirus, the search indexer, or a file-sync client (Dropbox, OneDrive), surfacing as a transient EPERM / EACCES / EBUSY on rename even though the temp file is fine. `b.atomicFile.writeSync` already retried this, but `b.httpClient.downloadStream` did not — a download into a cloud-synced or AV-scanned directory could fail hard on the lock. The retry is now the reusable `b.atomicFile.renameWithRetry`, and every final temp-to-destination rename in the framework routes through it: downloads, sealed vault keys, CA key/cert writes, log rotation, archive extraction, config-drift sidecars, the self-update binary swap, and restore/rollback moves. A non-transient error still throws immediately; POSIX renames are unaffected. **Detectors:** *Rename-retry, SQLite-limits, and Clear-Site-Data guards* — Three recurrence detectors ship with the fixes: a bare `nodeFs.renameSync` final rename that doesn't route through `atomicFile.renameWithRetry`; a main `DatabaseSync` handle constructed without the SQLITE_LIMIT_LENGTH `limits`; and a hand-rolled Clear-Site-Data header value that skips the shared RFC 9527 builder.
@@ -331,6 +331,15 @@ function isRowSealed(value) {
331
331
  * // threaded into AAD. Default "1". Bump
332
332
  * // when the column layout changes to
333
333
  * // invalidate all prior ciphertext.
334
+ * allowPlainMigration: boolean, // default false. On an aad / per-row-key
335
+ * // table the read path refuses a PLAIN
336
+ * // (unbound) vault: cell — a relocatable
337
+ * // envelope an attacker could copy in from
338
+ * // another row defeats the AAD copy-
339
+ * // protection, so it is nulled, not surfaced.
340
+ * // Set true ONLY for the bounded window while
341
+ * // migrating pre-AAD rows up to AAD-bound
342
+ * // ciphertext; clear it once migration ends.
334
343
  *
335
344
  * @example
336
345
  * b.cryptoField.registerTable("patients", {
@@ -403,6 +412,13 @@ function registerTable(name, opts) {
403
412
  rowIdField: rowIdField,
404
413
  schemaVersion: schemaVersion,
405
414
  derivedHashMode: derivedHashMode,
415
+ // allowPlainMigration — read-side downgrade window. On an aad / per-row-key
416
+ // table the read path refuses a plain `vault:` cell (no AAD = relocatable,
417
+ // which would defeat the cross-row/cross-column copy-protection the AAD
418
+ // binding advertises). Operators with genuine pre-AAD rows opt into a
419
+ // bounded lazy-migration window with { allowPlainMigration: true }; a
420
+ // re-seal (sealRow) then re-emits the cell AAD-bound. Default closed.
421
+ allowPlainMigration: opts.allowPlainMigration === true,
406
422
  };
407
423
  }
408
424
 
@@ -1240,6 +1256,20 @@ function unsealRow(table, row, actor, dbHandle) {
1240
1256
  unsealed = _decodeTyped(vaultAad.unseal(out[field],
1241
1257
  _aadParts(s, table, field, out)));
1242
1258
  } else if (typeof out[field] === "string" && out[field].startsWith(VAULT_PREFIX)) {
1259
+ // A plain `vault:` cell (no AAD) on an AAD-bound / per-row-key table
1260
+ // is a downgrade: plain vault.seal carries no AAD, so a DB-write
1261
+ // attacker could relocate such a cell from another row/column into
1262
+ // this one and the read would silently accept it — defeating the
1263
+ // cross-row/cross-column copy-protection the AAD binding advertises.
1264
+ // Refuse (throw -> catch nulls the field + audits) unless the table
1265
+ // opted into the documented pre-AAD lazy-migration window.
1266
+ if ((s.aad || perRowKeyTables[table]) && !s.allowPlainMigration) {
1267
+ throw new CryptoFieldError("crypto-field/aad-downgrade-refused",
1268
+ "unsealRow: '" + table + "'.'" + field + "' is AAD-bound but the stored " +
1269
+ "cell is a plain (unbound) vault envelope — refusing a relocatable-seal " +
1270
+ "downgrade (set registerTable({ allowPlainMigration: true }) for a " +
1271
+ "documented pre-AAD migration window)");
1272
+ }
1243
1273
  unsealed = _decodeTyped(vault.unseal(out[field]));
1244
1274
  } else {
1245
1275
  // Not a sealed value — pass through.
@@ -73,6 +73,18 @@ function _err(code, message) {
73
73
  return new DeclareRowPolicyError(code, message);
74
74
  }
75
75
 
76
+ // _isRlsEnabled — fail-closed coercion of pg_class.relrowsecurity. Native pg
77
+ // drivers return a JS boolean; a proxy / ORM / non-native driver may return
78
+ // "t"/"f", "true"/"false", or 1/0. RLS counts as enabled ONLY on a value that
79
+ // unambiguously means true; every other shape (including the truthy string
80
+ // "f") reads as not-enabled, so ENABLE is (re-)issued rather than silently
81
+ // skipped — a skipped ENABLE would leave the table's rows unprotected.
82
+ function _isRlsEnabled(v) {
83
+ if (v === true || v === 1) return true;
84
+ if (typeof v === "string") return /^(t|true|1|on|yes)$/i.test(v.trim());
85
+ return false;
86
+ }
87
+
76
88
  function _validateIdent(where, value) {
77
89
  try {
78
90
  safeSql.validateIdentifier(value, { allowReserved: true });
@@ -227,7 +239,14 @@ function declareRowPolicy(opts) {
227
239
  "source table '" + spec.schema + "." + spec.table +
228
240
  "' not found (does it exist? does the migration role have visibility?)");
229
241
  }
230
- if (!rows[0].relrowsecurity) {
242
+ // relrowsecurity is a Postgres boolean. Native pg drivers return true/false,
243
+ // but a proxy / ORM / non-native driver may hand back "t"/"f", "true"/"false",
244
+ // or 1/0. The string "f" is TRUTHY, so a bare `!rows[0].relrowsecurity` would
245
+ // read "f" as "already enabled" and silently SKIP ENABLE — leaving the table's
246
+ // rows unprotected while the migration reports success. Treat RLS as enabled
247
+ // ONLY on a value that unambiguously means true; anything else fails closed and
248
+ // (re-)issues ENABLE, which is a harmless no-op on an already-enabled table.
249
+ if (!_isRlsEnabled(rows[0].relrowsecurity)) {
231
250
  var enableStmt = sql.enableRowLevelSecurity(tableRef, { dialect: "postgres" });
232
251
  await xdb.query(enableStmt.sql, enableStmt.params);
233
252
  }
package/lib/db.js CHANGED
@@ -1402,6 +1402,13 @@ async function init(opts) {
1402
1402
  aad: t.aad,
1403
1403
  rowIdField: t.rowIdField,
1404
1404
  schemaVersion: t.schemaVersion,
1405
+ // The read-side pre-AAD migration opt-in must pass through too —
1406
+ // otherwise a schema declaring { aad: true, allowPlainMigration: true }
1407
+ // registers with the default (false) via this declarative db.init path,
1408
+ // and legacy plain vault: cells are nulled on read despite the operator
1409
+ // opting into the migration window. registerTable defaults this to false,
1410
+ // so non-migrating tables are unaffected.
1411
+ allowPlainMigration: t.allowPlainMigration,
1405
1412
  });
1406
1413
  tableMetadata[t.name] = {
1407
1414
  primaryKey: _normalizePk(t),
package/lib/guard-csv.js CHANGED
@@ -56,6 +56,7 @@
56
56
 
57
57
  var codepointClass = require("./codepoint-class");
58
58
  var csv = require("./csv");
59
+ var safeBuffer = require("./safe-buffer");
59
60
  var C = require("./constants");
60
61
  var lazyRequire = require("./lazy-require");
61
62
  var numericBounds = require("./numeric-bounds");
@@ -432,7 +433,9 @@ function _stripIssues(text, opts) {
432
433
  out = out.replace(ZW_RE_G, "");
433
434
  if (opts.trailingWhitespacePolicy === "trim") {
434
435
  out = out.split("\n").map(function (line) {
435
- return line.replace(/[ \t]+$/g, "");
436
+ // Linear per-line trailing-whitespace trim — .replace(/[ \t]+$/) is
437
+ // O(n^2) in V8 on adversarial input (untrusted CSV here).
438
+ return safeBuffer.stripTrailingHspace(line);
436
439
  }).join("\n");
437
440
  }
438
441
  return out;
@@ -521,9 +524,15 @@ function escapeCell(value, opts) {
521
524
  if (opts.bidiCharPolicy === "strip") str = str.replace(BIDI_RE_G, "");
522
525
 
523
526
  if (opts.trailingWhitespacePolicy === "trim") {
524
- str = str.replace(/[ \t]+$/g, "");
525
- } else if (opts.trailingWhitespacePolicy === "reject" && /[ \t]+$/.test(str)) {
526
- throw _err("csv.trailing-whitespace", "cell has trailing whitespace");
527
+ // Linear strip — .replace(/[ \t]+$/) is O(n^2) on adversarial untrusted CSV.
528
+ str = safeBuffer.stripTrailingHspace(str);
529
+ } else if (opts.trailingWhitespacePolicy === "reject") {
530
+ // Linear "ends in space/tab?" check — /[ \t]+$/.test is ALSO O(n^2) (the
531
+ // engine scans from every offset when there is no trailing run).
532
+ var lastCode = str.length > 0 ? str.charCodeAt(str.length - 1) : 0;
533
+ if (lastCode === 0x20 || lastCode === 0x09) {
534
+ throw _err("csv.trailing-whitespace", "cell has trailing whitespace");
535
+ }
527
536
  }
528
537
 
529
538
  if (typeof value === "number" &&
package/lib/mail-bimi.js CHANGED
@@ -799,10 +799,23 @@ async function fetchAndVerifyMark(opts) {
799
799
 
800
800
  function _splitPemChain(pemText) {
801
801
  if (typeof pemText !== "string") return [];
802
+ // Linear indexOf walk over non-overlapping BEGIN..END blocks — NOT
803
+ // /-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g. The
804
+ // lazy-quantifier scan re-walks from every BEGIN marker that has no
805
+ // matching END, which is superlinear on a chain of BEGIN-only markers;
806
+ // the indexOf walk advances monotonically and never re-scans.
807
+ var BEGIN = "-----BEGIN CERTIFICATE-----";
808
+ var END = "-----END CERTIFICATE-----";
802
809
  var out = [];
803
- var re = /-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g;
804
- var m;
805
- while ((m = re.exec(pemText)) !== null) out.push(m[0]);
810
+ var from = 0;
811
+ for (;;) {
812
+ var b = pemText.indexOf(BEGIN, from);
813
+ if (b === -1) break;
814
+ var e = pemText.indexOf(END, b + BEGIN.length);
815
+ if (e === -1) break; // unterminated final block — no further certs
816
+ out.push(pemText.slice(b, e + END.length));
817
+ from = e + END.length;
818
+ }
806
819
  return out;
807
820
  }
808
821
 
package/lib/mail.js CHANGED
@@ -313,10 +313,9 @@ function _normalizeRecipientList(value, label) {
313
313
  label + "[" + i + "] contains forbidden control characters", true);
314
314
  }
315
315
  // Accept "Name <email@addr>" form too — extract the angle-bracket
316
- // address for validation; preserve the full string in the message.
317
- var bracket = arr[i].match(/<([^>]+)>/);
318
- var addr = bracket ? bracket[1] : arr[i];
319
- if (!_isValidEmail(addr.trim())) {
316
+ // address for validation (linear, via _extractAddr); preserve the full
317
+ // string in the message.
318
+ if (!_isValidEmail(_extractAddr(arr[i]))) {
320
319
  throw new MailError("mail/invalid-recipient",
321
320
  label + " '" + arr[i] + "' is not a valid email address", true);
322
321
  }
@@ -423,9 +422,7 @@ function _validateMessage(message) {
423
422
  throw new MailError("mail/invalid-from",
424
423
  "message.from contains forbidden control characters", true);
425
424
  }
426
- var fromBracket = message.from.match(/<([^>]+)>/);
427
- var fromAddr = fromBracket ? fromBracket[1] : message.from;
428
- if (!_isValidEmail(fromAddr.trim())) {
425
+ if (!_isValidEmail(_extractAddr(message.from))) {
429
426
  throw new MailError("mail/invalid-from",
430
427
  "message.from '" + message.from + "' is not a valid email address", true);
431
428
  }
@@ -557,8 +554,18 @@ function _mergeMessage(defaults, message) {
557
554
 
558
555
  function _extractAddr(s) {
559
556
  if (s === undefined || s === null) return s;
560
- var m = String(s).match(/<([^>]+)>/);
561
- return m ? m[1].trim() : String(s).trim();
557
+ s = String(s);
558
+ // Linear angle-bracket extraction — NOT s.match(/<([^>]+)>/), which is O(n^2)
559
+ // in V8 on a long run of '<' with no '>' (the engine retries the greedy
560
+ // [^>]+ from every '<' offset; 200K '<' ~ 11s). Recipient/from addresses on
561
+ // b.mail.send can be caller/request-supplied, so this is a reachable DoS.
562
+ // Mirrors the regex: the chars between the first '<' and the next '>'.
563
+ var lt = s.indexOf("<");
564
+ if (lt !== -1) {
565
+ var gt = s.indexOf(">", lt + 1);
566
+ if (gt > lt + 1) return s.slice(lt + 1, gt).trim();
567
+ }
568
+ return s.trim();
562
569
  }
563
570
 
564
571
  function _toArray(v) {
package/lib/mcp.js CHANGED
@@ -435,7 +435,28 @@ var PROMPT_INJECTION_MARKERS = [
435
435
  "</?(?:assistant|system|user|tool)>",
436
436
  ];
437
437
  var INJECTION_RE = new RegExp(PROMPT_INJECTION_MARKERS.join("|"), "i"); // allow:dynamic-regex — composed from the const PROMPT_INJECTION_MARKERS list above; not operator-supplied input
438
- var DANGEROUS_HTML_RE = /<script\b|<iframe\b|<object\b|<embed\b|javascript:/i;
438
+ // vbscript: and data:text/html are dangerous URL schemes the guard claims to
439
+ // neutralize but the original alternation omitted (CodeQL js/incomplete-url-
440
+ // scheme-check). data: is scoped to text/html so a benign data:image/png isn't
441
+ // over-redacted. The alternation stays linear (no nested quantifier).
442
+ var DANGEROUS_HTML_RE = /<script\b|<iframe\b|<object\b|<embed\b|javascript:|vbscript:|data:\s*text\/html/i;
443
+
444
+ // Global variants for sanitize-mode redaction. A non-global .replace removes
445
+ // only the LEFTMOST match, so on `data:text/html,<script>alert(1)</script>`
446
+ // the leftmost `data:text/html` would be stripped and the executable
447
+ // `<script>` left behind — sanitize mode returning runnable HTML. _redactAll
448
+ // replaces EVERY dangerous token, repeating to a fixpoint in case removing one
449
+ // abuts two halves into a new one. Input byte-length is bounded by the caller,
450
+ // and [REDACTED] introduces no dangerous token, so the loop terminates quickly.
451
+ var INJECTION_RE_G = new RegExp(PROMPT_INJECTION_MARKERS.join("|"), "gi"); // allow:dynamic-regex — same const-composed source as INJECTION_RE
452
+ var DANGEROUS_HTML_RE_G = /<script\b|<iframe\b|<object\b|<embed\b|javascript:|vbscript:|data:\s*text\/html/gi;
453
+
454
+ function _redactAll(text, globalRe) {
455
+ var out = text;
456
+ var prev;
457
+ do { prev = out; out = out.replace(globalRe, "[REDACTED]"); } while (out !== prev);
458
+ return out;
459
+ }
439
460
 
440
461
  function _toolResultSanitize(result, opts) {
441
462
  opts = opts || {};
@@ -475,14 +496,15 @@ function _toolResultSanitize(result, opts) {
475
496
  if (INJECTION_RE.test(regexInput)) { // allow:regex-no-length-cap regexInput byteLength bounded above
476
497
  issues.push({ kind: "prompt-injection", index: i });
477
498
  if (posture === "sanitize") {
478
- // Strip the injection marker line — operators wanting
479
- // structural redaction wire their own classifier.
480
- t = t.replace(INJECTION_RE, "[REDACTED]");
499
+ // Strip EVERY injection marker — operators wanting structural
500
+ // redaction wire their own classifier. Global fixpoint redact so a
501
+ // second marker after the first isn't left behind.
502
+ t = _redactAll(t, INJECTION_RE_G);
481
503
  }
482
504
  }
483
505
  if (DANGEROUS_HTML_RE.test(regexInput)) { // allow:regex-no-length-cap regexInput byteLength bounded above
484
506
  issues.push({ kind: "dangerous-html", index: i });
485
- if (posture === "sanitize") t = t.replace(DANGEROUS_HTML_RE, "[REDACTED]");
507
+ if (posture === "sanitize") t = _redactAll(t, DANGEROUS_HTML_RE_G);
486
508
  }
487
509
  cleaned.push({ type: "text", text: t });
488
510
  } else if (block.type === "image" || block.type === "resource_link" || block.type === "audio") {
@@ -922,7 +944,7 @@ function _elicitationGuard(opts) {
922
944
  }
923
945
  if (posture === "sanitize") {
924
946
  return Object.assign({}, elicitRequest, {
925
- message: message.replace(INJECTION_RE, "[REDACTED]"),
947
+ message: _redactAll(message, INJECTION_RE_G),
926
948
  });
927
949
  }
928
950
  }
@@ -29,6 +29,7 @@
29
29
  var defineClass = require("../framework-error").defineClass;
30
30
  var lazyRequire = require("../lazy-require");
31
31
  var validateOpts = require("../validate-opts");
32
+ var safeBuffer = require("../safe-buffer");
32
33
 
33
34
  var audit = lazyRequire(function () { return require("../audit"); });
34
35
 
@@ -140,11 +141,12 @@ function create(opts) {
140
141
  if (typeof ct !== "string" || ct.indexOf("text/html") === -1) return chunk;
141
142
  var body = Buffer.isBuffer(chunk) ? chunk.toString("utf8") :
142
143
  (typeof chunk === "string" ? chunk : "");
143
- // Inject after <body> opening tag if present, else after <html>
144
- // opening tag, else prepend.
145
- var bodyMatch = body.match(/<body[^>]*>/i);
146
- if (bodyMatch) {
147
- var idx = bodyMatch.index + bodyMatch[0].length;
144
+ // Inject after the <body> opening tag if present, else prepend.
145
+ // Linear tag-find — NOT body.match(/<body[^>]*>/i), which is O(n^2)
146
+ // in V8 on a body carrying many `<body` starts with no closing `>`
147
+ // (rendered user content can produce exactly that).
148
+ var idx = safeBuffer.indexAfterOpenTag(body, "body");
149
+ if (idx !== -1) {
148
150
  body = body.slice(0, idx) + "\n" + bannerHtml + "\n" + body.slice(idx);
149
151
  } else {
150
152
  body = bannerHtml + "\n" + body;
@@ -65,6 +65,7 @@
65
65
  */
66
66
 
67
67
  var validateOpts = require("../validate-opts");
68
+ var safeBuffer = require("../safe-buffer");
68
69
 
69
70
  // Per W3C draft + Chromium implementation. `immediate` triggers the
70
71
  // speculation as soon as the rules are seen; `conservative` waits
@@ -287,10 +288,11 @@ function create(opts) {
287
288
  if (headClose !== -1) {
288
289
  body = body.slice(0, headClose) + tag + body.slice(headClose);
289
290
  } else {
290
- var bodyOpen = body.match(/<body[^>]*>/i);
291
- if (bodyOpen) {
292
- var idx = bodyOpen.index + bodyOpen[0].length;
293
- body = body.slice(0, idx) + tag + body.slice(idx);
291
+ // Linear tag-find — NOT body.match(/<body[^>]*>/i) (O(n^2) in V8
292
+ // on a body with many `<body` starts and no closing `>`).
293
+ var bodyIdx = safeBuffer.indexAfterOpenTag(body, "body");
294
+ if (bodyIdx !== -1) {
295
+ body = body.slice(0, bodyIdx) + tag + body.slice(bodyIdx);
294
296
  } else {
295
297
  // No <head> or <body> — prepend so the rules at least
296
298
  // reach the parser. This matches the bot-disclose fallback.
@@ -147,7 +147,7 @@ function parse(input, opts) {
147
147
  if (eqIdx < 0) {
148
148
  throw new SafeEnvError("missing '=' separator", "env/bad-line", lineNumber);
149
149
  }
150
- var key = trimmed.substring(0, eqIdx).replace(safeBuffer.TRAILING_HSPACE_RE, "");
150
+ var key = safeBuffer.stripTrailingHspace(trimmed.substring(0, eqIdx));
151
151
  var rest = trimmed.substring(eqIdx + 1);
152
152
 
153
153
  if (key.length === 0) {
@@ -186,10 +186,13 @@ function parse(input, opts) {
186
186
  // The comment marker MUST be preceded by whitespace to count
187
187
  // (so a value like `KEY=color#red` keeps the literal `#`).
188
188
  var commentMatch = rest.match(/^([^\s#]*(?:[ \t]+[^#\s]+)*)\s+#.*$/);
189
+ // stripTrailingHspace is a linear char-scan; .replace(/[ \t]+$/) is O(n^2)
190
+ // in V8 and the env parser only caps TOTAL bytes, not per-line, so a
191
+ // single huge-whitespace value line would otherwise hang the parser.
189
192
  if (commentMatch) {
190
- value = commentMatch[1].replace(safeBuffer.TRAILING_HSPACE_RE, "");
193
+ value = safeBuffer.stripTrailingHspace(commentMatch[1]);
191
194
  } else {
192
- value = rest.replace(safeBuffer.TRAILING_HSPACE_RE, "");
195
+ value = safeBuffer.stripTrailingHspace(rest);
193
196
  }
194
197
  // Reject `$VAR` style references — explicit error so operators
195
198
  // see the policy rather than silently getting unexpanded text.
@@ -185,7 +185,7 @@ function parse(input, opts) {
185
185
  var raw = rawLines[i];
186
186
  // Strip trailing whitespace from the line for analysis (block-scalar
187
187
  // content paths preserve their own internal spacing separately).
188
- var trimmed = raw.replace(safeBuffer.TRAILING_HSPACE_RE, "");
188
+ var trimmed = safeBuffer.stripTrailingHspace(raw);
189
189
  var indent = 0;
190
190
  while (indent < raw.length && raw.charAt(indent) === " ") indent += 1;
191
191
  if (indent < raw.length && raw.charAt(indent) === "\t") {
@@ -332,7 +332,7 @@ function parse(input, opts) {
332
332
  if (raw.charAt(0) === "'") {
333
333
  return _decodeSingleQuoted(raw, lineNumber, col);
334
334
  }
335
- var trimmed = raw.replace(safeBuffer.TRAILING_HSPACE_RE, "");
335
+ var trimmed = safeBuffer.stripTrailingHspace(raw);
336
336
  if (POISONED_KEYS.has(trimmed)) {
337
337
  throw new SafeYamlError("forbidden key '" + trimmed + "'",
338
338
  "yaml/poisoned-key", lineNumber, col);
@@ -506,7 +506,7 @@ function parse(input, opts) {
506
506
  return sq;
507
507
  }
508
508
  // Plain scalar — strip trailing space, resolve type.
509
- return _resolveScalar(t.replace(safeBuffer.TRAILING_HSPACE_RE, ""));
509
+ return _resolveScalar(safeBuffer.stripTrailingHspace(t));
510
510
  }
511
511
 
512
512
  // For quoted-string termination check on a single-line value.
@@ -622,7 +622,7 @@ function parse(input, opts) {
622
622
  if (c === "," || c === "}" || c === "]") break;
623
623
  p += 1;
624
624
  }
625
- var raw = text.substring(start, p).replace(safeBuffer.TRAILING_HSPACE_RE, "");
625
+ var raw = safeBuffer.stripTrailingHspace(text.substring(start, p));
626
626
  return { value: _resolveScalar(raw), nextPos: p };
627
627
  }
628
628
 
@@ -645,7 +645,7 @@ function parse(input, opts) {
645
645
  if (c === ":" || c === "," || c === "}" || c === "]") break;
646
646
  p += 1;
647
647
  }
648
- return { key: text.substring(start, p).replace(safeBuffer.TRAILING_HSPACE_RE, ""), nextPos: p };
648
+ return { key: safeBuffer.stripTrailingHspace(text.substring(start, p)), nextPos: p };
649
649
  }
650
650
 
651
651
  function _findMatchingBracket(text, start, open, close, lineNumber, col) {
@@ -772,7 +772,7 @@ function parse(input, opts) {
772
772
  function _stripEolComment(text) {
773
773
  // Strip ` #...` comments (must be preceded by whitespace) at end of line.
774
774
  var match = text.match(/^(.*?)(\s+#.*)?$/);
775
- return (match && match[1] != null ? match[1] : text).replace(safeBuffer.TRAILING_HSPACE_RE, "");
775
+ return safeBuffer.stripTrailingHspace(match && match[1] != null ? match[1] : text);
776
776
  }
777
777
 
778
778
  // ---- Block scalars (| literal, > folded) ----
@@ -494,7 +494,74 @@ var TRAILING_HSPACE_RE = /[ \t]+$/;
494
494
  */
495
495
  function stripTrailingHspace(s) {
496
496
  if (typeof s !== "string") return s;
497
- return s.replace(TRAILING_HSPACE_RE, "");
497
+ // Linear backward scan over trailing spaces/tabs — NOT s.replace(/[ \t]+$/).
498
+ // The `$`-after-greedy-`[ \t]+` regex is O(n^2) in V8 on adversarial input
499
+ // (a long run of spaces followed by a non-space: the engine retries the
500
+ // greedy match from every offset). normalizeText callers cap TOTAL bytes but
501
+ // not per-line, so a single ~500K-space value hangs (~85s). The char-scan is
502
+ // O(trailing-whitespace) and byte-identical to the regex on every input
503
+ // (JS `$` without /m matches only the absolute end, so a trailing \n is not
504
+ // stripped — the scan stops at it too).
505
+ var e = s.length;
506
+ while (e > 0) {
507
+ var c = s.charCodeAt(e - 1);
508
+ if (c === 0x20 || c === 0x09) { e -= 1; } else { break; }
509
+ }
510
+ return e === s.length ? s : s.slice(0, e);
511
+ }
512
+
513
+ /**
514
+ * @primitive b.safeBuffer.indexAfterOpenTag
515
+ * @signature b.safeBuffer.indexAfterOpenTag(html, tagName)
516
+ * @since 0.15.11
517
+ * @related b.safeBuffer.stripTrailingHspace
518
+ *
519
+ * Find the offset in `html` just past the first `<tagName ...>` opening
520
+ * tag (case-insensitive), or `-1` when the tag is absent or unterminated.
521
+ * The insertion point a response rewriter uses to splice content right
522
+ * after `<body>` / `<head>` without a regex.
523
+ *
524
+ * This replaces the `html.match(/<body[^>]*>/i)` shape, which is O(n^2)
525
+ * in V8: a body carrying many `<body` starts with no closing `>` (e.g.
526
+ * rendered user content) makes the engine retry the greedy `[^>]*` from
527
+ * every offset — a `<body`-repeated 200K-char body benchmarks in
528
+ * seconds. This is a single forward `indexOf` walk: linear in the input,
529
+ * and stricter than the regex — it requires a real tag boundary after
530
+ * the name (whitespace, `>`, or `/`), so `<bodyfoo>` is not mistaken for
531
+ * `<body>`. Non-string input returns `-1`.
532
+ *
533
+ * @example
534
+ * var b = require("blamejs");
535
+ * b.safeBuffer.indexAfterOpenTag("<html><body class=x>hi", "body");
536
+ * // → 19 (just past the '>' of <body class=x>)
537
+ *
538
+ * b.safeBuffer.indexAfterOpenTag("<p>no body here</p>", "body");
539
+ * // → -1
540
+ */
541
+ function indexAfterOpenTag(html, tagName) {
542
+ if (typeof html !== "string" || typeof tagName !== "string" || tagName.length === 0) return -1;
543
+ var needle = "<" + tagName.toLowerCase();
544
+ var nlen = needle.length;
545
+ // One O(n) lowercase pass keeps the case-insensitive search linear; the
546
+ // forward indexOf walk below never re-scans a region it has passed.
547
+ var lower = html.toLowerCase();
548
+ var from = 0;
549
+ for (;;) {
550
+ var lt = lower.indexOf(needle, from);
551
+ if (lt === -1) return -1;
552
+ var after = lt + nlen;
553
+ var boundary = after < html.length ? html.charCodeAt(after) : -1;
554
+ // The char after "<tag" must end the tag name — '>' (0x3e), '/' (0x2f),
555
+ // or ASCII whitespace — else this is a longer name like "<bodyfoo".
556
+ if (boundary === 0x3e || boundary === 0x2f ||
557
+ boundary === 0x20 || boundary === 0x09 ||
558
+ boundary === 0x0a || boundary === 0x0d || boundary === 0x0c) {
559
+ var gt = html.indexOf(">", after);
560
+ if (gt === -1) return -1; // unterminated opening tag — no insertion point
561
+ return gt + 1;
562
+ }
563
+ from = lt + 1;
564
+ }
498
565
  }
499
566
 
500
567
  /**
@@ -612,6 +679,7 @@ module.exports = {
612
679
  hasCrlf: hasCrlf,
613
680
  stripCrlf: stripCrlf,
614
681
  stripTrailingHspace: stripTrailingHspace,
682
+ indexAfterOpenTag: indexAfterOpenTag,
615
683
  HEX_RE: HEX_RE,
616
684
  BASE64URL_RE: BASE64URL_RE,
617
685
  BASE64_RE: BASE64_RE,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.15.10",
3
+ "version": "0.15.11",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:67b3105d-f49c-44bd-bf4e-afbb994d35e2",
5
+ "serialNumber": "urn:uuid:693c533d-2a9b-43e7-93e5-01669defbb95",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-06-14T03:47:28.687Z",
8
+ "timestamp": "2026-06-14T07:19:57.070Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/core@0.15.10",
22
+ "bom-ref": "@blamejs/core@0.15.11",
23
23
  "type": "application",
24
24
  "name": "blamejs",
25
- "version": "0.15.10",
25
+ "version": "0.15.11",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "The Node framework that owns its stack.",
29
- "purl": "pkg:npm/%40blamejs/core@0.15.10",
29
+ "purl": "pkg:npm/%40blamejs/core@0.15.11",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/core@0.15.10",
57
+ "ref": "@blamejs/core@0.15.11",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]