From ef7b0491e23dd4dab8e061c9fcd8fc3dc96c9a73 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 20:44:45 +0000 Subject: [PATCH 1/2] fix(typescript): vendor ZapCode on every target and cap padStart/padEnd zapcode-core 1.5.1 collects padStart/padEnd padding with no size check, so 'a'.padStart(2**40) reserves ~1 TiB and the failed allocation aborts the host process with every tenant (security audit F5). Native builds now use the in-tree ZapCode copy the browser build already used (renamed zapcode_browser -> zapcode_vendor) and drop the registry crate; the copy carries a marked fork edit capping the target length at 10,000,000 like upstream repeat. The drift check lists fork edits and rejects unlisted markers. TM-TS-025. --- .github/dependabot.yml | 31 ++++--------- .github/workflows/ci.yml | 4 +- Cargo.lock | 18 -------- crates/bashkit/Cargo.toml | 19 ++++---- crates/bashkit/src/builtins/typescript.rs | 3 +- crates/bashkit/src/lib.rs | 20 ++++---- crates/bashkit/src/zapcode_browser/README.md | 10 ---- .../LICENSE | 0 crates/bashkit/src/zapcode_vendor/README.md | 12 +++++ .../compiler/instruction.rs | 0 .../compiler/mod.rs | 4 +- .../error.rs | 0 .../mod.rs | 0 .../parser/ir.rs | 0 .../parser/mod.rs | 2 +- .../sandbox.rs | 12 ++--- .../snapshot.rs | 10 ++-- .../trace.rs | 0 .../upstream-sha256.json | 0 .../value.rs | 0 .../vm/builtins.rs | 8 +++- .../vm/mod.rs | 20 ++++---- .../tests/integration/threat_model_tests.rs | 28 +++++++++++ knowledge/log.md | 4 ++ knowledge/operations/dependencies.md | 32 ++++++------- knowledge/runtimes/zapcode-runtime.md | 46 ++++++++++++------- knowledge/security/threat-model.md | 1 + scripts/check_zapcode_browser.py | 23 ---------- scripts/check_zapcode_vendor.py | 46 +++++++++++++++++++ supply-chain/config.toml | 4 -- 30 files changed, 193 insertions(+), 164 deletions(-) delete mode 100644 crates/bashkit/src/zapcode_browser/README.md rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/LICENSE (100%) create mode 100644 crates/bashkit/src/zapcode_vendor/README.md rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/compiler/instruction.rs (100%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/compiler/mod.rs (99%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/error.rs (100%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/mod.rs (100%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/parser/ir.rs (100%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/parser/mod.rs (99%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/sandbox.rs (81%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/snapshot.rs (92%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/trace.rs (100%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/upstream-sha256.json (100%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/value.rs (100%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/vm/builtins.rs (98%) rename crates/bashkit/src/{zapcode_browser => zapcode_vendor}/vm/mod.rs (99%) delete mode 100644 scripts/check_zapcode_browser.py create mode 100644 scripts/check_zapcode_vendor.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 2bf156ed9..036086d53 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -118,28 +118,15 @@ updates: # rationale sits next to the dep in the root Cargo.toml. - dependency-name: "branches" - # oxc_* is held at 0.117.x, and not for API churn alone. bashkit declares - # these five (`oxc_parser`, `oxc_ast`, `oxc_allocator`, `oxc_span`, - # `oxc_syntax`) for the wasm32-unknown-unknown TypeScript path, where - # `zapcode_browser/parser` walks the oxc AST directly. The versions exist - # to match what upstream `zapcode-core` vendors — see the pin comment next - # to the deps in crates/bashkit/Cargo.toml. - # - # `zapcode-core` 1.5.1 requires `oxc ^0.117`, so it does not move with a - # bump of bashkit's declaration. #2758 bumped to 0.154.0 and resolved a - # *second* copy of all 13 oxc crates, leaving the two sides of the same - # parser pipeline on trees 37 minor versions apart — and 0.154 also needs - # rustc 1.97.0 against the 1.95.0 in rust-toolchain.toml, which is what - # reddened the "WASM web package" job, the same shape as the wasmtime - # 49.x failure in #2708. It also pulled in 19 unvetted crates - # (`compact_str` 0.10, `phf` 0.14, `oxc_index` 5.0 and the oxc stack). - # - # Ignore outright rather than by update-type: every release past 0.117.x - # splits the graph the same way, so no bump helps until `zapcode-core` - # moves upstream. Doing it then means bumping the pinned toolchain and - # porting the vendored parser together — a deliberate change, not an - # aggregated `chore(deps)` PR. Without this entry dependabot reopens the - # same unlandable PR every week. + # oxc_* is held at 0.117.x. bashkit declares these five (`oxc_parser`, + # `oxc_ast`, `oxc_allocator`, `oxc_span`, `oxc_syntax`) for the vendored + # ZapCode 1.5.1 copy (`zapcode_vendor/parser` walks the oxc AST directly), + # used on every target. Any oxc release past 0.117.x changes that AST, and + # #2758 (0.154.0) also needed a newer rustc than rust-toolchain.toml. + # Moving oxc means porting the vendored parser and bumping the toolchain + # together, a deliberate change, not an aggregated `chore(deps)` PR. + # Without this entry dependabot reopens the same unlandable PR every week. + # See knowledge/operations/dependencies.md. - dependency-name: "oxc_*" # Fuzz targets are a separate cargo workspace with their own lockfile, so the diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab84b8fd1..bf7c8f659 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,8 +95,8 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 - - name: Check browser VM source drift - run: python3 scripts/check_zapcode_browser.py + - name: Check vendored ZapCode source drift + run: python3 scripts/check_zapcode_vendor.py - name: Check bashkit for wasm32-unknown-unknown run: cargo check -p bashkit -p bashkit-scripted-tool --target wasm32-unknown-unknown --features bashkit/jq,bashkit/wasm_js,bashkit/terminal diff --git a/Cargo.lock b/Cargo.lock index 372e29623..e395ad441 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -512,7 +512,6 @@ dependencies = [ "wasm-bindgen-futures", "wasmtime", "web-time", - "zapcode-core", "zeroize", ] @@ -7988,23 +7987,6 @@ dependencies = [ "synstructure", ] -[[package]] -name = "zapcode-core" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "763b84cb268f5cf5212198eff31106006ac32aa7e472201cae9f994521abebe2" -dependencies = [ - "indexmap", - "oxc_allocator", - "oxc_ast", - "oxc_parser", - "oxc_span", - "oxc_syntax", - "postcard", - "serde", - "thiserror", -] - [[package]] name = "zerocopy" version = "0.8.56" diff --git a/crates/bashkit/Cargo.toml b/crates/bashkit/Cargo.toml index c6fcea373..6247c2988 100644 --- a/crates/bashkit/Cargo.toml +++ b/crates/bashkit/Cargo.toml @@ -76,6 +76,13 @@ bytes = { version = "1", default-features = false, optional = true } foldhash = { version = "0.2", default-features = false, optional = true } hifijson = { version = "0.5.0", default-features = false, features = ["alloc", "std"], optional = true } indexmap = { version = "2.0", default-features = false, optional = true } +# Vendored ZapCode (src/zapcode_vendor) uses the same parser/codec versions as upstream 1.5.1. +oxc_parser = { version = "0.117.0", optional = true } +oxc_ast = { version = "0.117.0", optional = true } +oxc_allocator = { version = "0.117.0", optional = true } +oxc_span = { version = "0.117.0", optional = true } +oxc_syntax = { version = "0.117.0", optional = true } +postcard = { version = "1.1.3", features = ["alloc"], optional = true } num-bigint = { version = "0.4.6", default-features = false, optional = true } ryu = { version = "1.0.20", optional = true } self_cell = { version = "1.2.0", optional = true } @@ -252,7 +259,7 @@ cpython = ["dep:bashkit-cpython-wasm", "dep:wasmtime"] cpython-native = ["cpython", "bashkit-cpython-wasm/native"] # Enable ts/node/deno/bun builtins via embedded ZapCode TypeScript interpreter # Usage: cargo build --features typescript -typescript = ["dep:zapcode-core", "dep:oxc_parser", "dep:oxc_ast", "dep:oxc_allocator", "dep:oxc_span", "dep:oxc_syntax", "dep:postcard", "dep:indexmap", "indexmap/serde", "serde/rc"] +typescript = ["dep:oxc_parser", "dep:oxc_ast", "dep:oxc_allocator", "dep:oxc_span", "dep:oxc_syntax", "dep:postcard", "dep:indexmap", "indexmap/std", "indexmap/serde", "serde/rc"] # Enable sqlite/sqlite3 builtins backed by Turso (pure-Rust SQLite-compatible # engine). Phase 1 uses turso's `MemoryIO` with a load/flush against the VFS # at command boundaries; Phase 2 plugs the bashkit VFS in via a custom `IO` @@ -450,14 +457,6 @@ fetchkit = { version = "0.7.1", default-features = false, features = ["docs-pdf" web-time = { workspace = true, optional = true } [target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] -# Vendored browser ZapCode uses the same parser/codec versions as upstream. -oxc_parser = { version = "0.117.0", optional = true } -oxc_ast = { version = "0.117.0", optional = true } -oxc_allocator = { version = "0.117.0", optional = true } -oxc_span = { version = "0.117.0", optional = true } -oxc_syntax = { version = "0.117.0", optional = true } -postcard = { version = "1.1.3", features = ["alloc"], optional = true } - gloo-timers = { version = "0.4", features = ["futures"], optional = true } send_wrapper = { version = "0.6", features = ["futures"], optional = true } # Task spawner for the host-call execution driver (see host_call.rs). JS-backed @@ -479,5 +478,3 @@ unexpected_cfgs = { level = "warn", check-cfg = ['cfg(feature, values("i18n-deci [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] tokio = { workspace = true, features = ["process"] } -[target.'cfg(not(all(target_arch = "wasm32", target_os = "unknown")))'.dependencies] -zapcode-core = { version = "1.5.1", optional = true } diff --git a/crates/bashkit/src/builtins/typescript.rs b/crates/bashkit/src/builtins/typescript.rs index c4a2d9aec..407d3cac8 100644 --- a/crates/bashkit/src/builtins/typescript.rs +++ b/crates/bashkit/src/builtins/typescript.rs @@ -16,8 +16,7 @@ //! `node`/`deno`/`bun` aliases. use crate::time_compat::Instant; -#[cfg(all(target_arch = "wasm32", target_os = "unknown"))] -use crate::zapcode_browser as zapcode_core; +use crate::zapcode_vendor as zapcode_core; use async_trait::async_trait; use std::future::Future; use std::path::{Path, PathBuf}; diff --git a/crates/bashkit/src/lib.rs b/crates/bashkit/src/lib.rs index d55f16409..1915d1c99 100644 --- a/crates/bashkit/src/lib.rs +++ b/crates/bashkit/src/lib.rs @@ -610,14 +610,9 @@ pub use builtins::{ TypeScriptConfig, TypeScriptExtension, TypeScriptExternalFnHandler, TypeScriptExternalFns, TypeScriptLimits, }; -// Re-export zapcode-core types needed by external handler consumers. -#[cfg(all(feature = "typescript", target_arch = "wasm32", target_os = "unknown"))] -pub use zapcode_browser::Value as ZapcodeValue; -#[cfg(all( - feature = "typescript", - not(all(target_arch = "wasm32", target_os = "unknown")) -))] -pub use zapcode_core::Value as ZapcodeValue; +// Re-export ZapCode types needed by external handler consumers. +#[cfg(feature = "typescript")] +pub use zapcode_vendor::Value as ZapcodeValue; /// Logging utilities module /// @@ -8721,9 +8716,10 @@ echo missing fi"#, } } -// Browser-only upstream source retains VM limits; native builds keep the -// external crate and its public value types. See runtimes/zapcode-runtime.md. -#[cfg(all(feature = "typescript", target_arch = "wasm32", target_os = "unknown"))] +// Decision: every target runs this in-tree ZapCode 1.5.1 copy instead of the +// registry crate, so Bashkit can carry resource-limit fixes (marked +// `bashkit fork:`) that upstream has not shipped. See runtimes/zapcode-runtime.md. +#[cfg(feature = "typescript")] #[rustfmt::skip] #[allow(dead_code, unused_imports, clippy::all, clippy::unwrap_used)] -mod zapcode_browser; +mod zapcode_vendor; diff --git a/crates/bashkit/src/zapcode_browser/README.md b/crates/bashkit/src/zapcode_browser/README.md deleted file mode 100644 index 650875b64..000000000 --- a/crates/bashkit/src/zapcode_browser/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Browser ZapCode source - -Upstream `zapcode-core` 1.5.1, MIT, https://github.com/TheUncharted/zapcode. -Native builds continue to use the registry crate and its original value types. -The browser copy allows replacing unsupported std clocks while preserving VM -resource enforcement; it adds no JS eval, imports, network or filesystem access. - -`upstream-sha256.json` records every original source file. Mechanical change: -`crate::` becomes `crate::zapcode_browser::`; `lib.rs` becomes `mod.rs`. -Clock changes in sandbox.rs/trace.rs use Bashkit's platform clock shim. diff --git a/crates/bashkit/src/zapcode_browser/LICENSE b/crates/bashkit/src/zapcode_vendor/LICENSE similarity index 100% rename from crates/bashkit/src/zapcode_browser/LICENSE rename to crates/bashkit/src/zapcode_vendor/LICENSE diff --git a/crates/bashkit/src/zapcode_vendor/README.md b/crates/bashkit/src/zapcode_vendor/README.md new file mode 100644 index 000000000..613fa5ded --- /dev/null +++ b/crates/bashkit/src/zapcode_vendor/README.md @@ -0,0 +1,12 @@ +# Vendored ZapCode source + +Upstream `zapcode-core` 1.5.1, MIT, https://github.com/TheUncharted/zapcode. +Every target (native, WASI, browser) builds this copy; the registry crate is +no longer a dependency. The copy replaces std clocks that panic on +wasm32-unknown-unknown and carries `bashkit fork:` resource-limit fixes +upstream has not shipped (listed in `scripts/check_zapcode_vendor.py`). It adds +no JS eval, imports, network or filesystem access. + +`upstream-sha256.json` records every original source file. Mechanical change: +`crate::` becomes `crate::zapcode_vendor::`; `lib.rs` becomes `mod.rs`. +Clock changes in sandbox.rs/trace.rs use Bashkit's platform clock shim. diff --git a/crates/bashkit/src/zapcode_browser/compiler/instruction.rs b/crates/bashkit/src/zapcode_vendor/compiler/instruction.rs similarity index 100% rename from crates/bashkit/src/zapcode_browser/compiler/instruction.rs rename to crates/bashkit/src/zapcode_vendor/compiler/instruction.rs diff --git a/crates/bashkit/src/zapcode_browser/compiler/mod.rs b/crates/bashkit/src/zapcode_vendor/compiler/mod.rs similarity index 99% rename from crates/bashkit/src/zapcode_browser/compiler/mod.rs rename to crates/bashkit/src/zapcode_vendor/compiler/mod.rs index a2685e1ca..b94733921 100644 --- a/crates/bashkit/src/zapcode_browser/compiler/mod.rs +++ b/crates/bashkit/src/zapcode_vendor/compiler/mod.rs @@ -2,8 +2,8 @@ pub mod instruction; use std::collections::{HashMap, HashSet}; -use crate::zapcode_browser::error::{Result, ZapcodeError}; -use crate::zapcode_browser::parser::ir::*; +use crate::zapcode_vendor::error::{Result, ZapcodeError}; +use crate::zapcode_vendor::parser::ir::*; use instruction::*; /// Compiled program ready for VM execution. diff --git a/crates/bashkit/src/zapcode_browser/error.rs b/crates/bashkit/src/zapcode_vendor/error.rs similarity index 100% rename from crates/bashkit/src/zapcode_browser/error.rs rename to crates/bashkit/src/zapcode_vendor/error.rs diff --git a/crates/bashkit/src/zapcode_browser/mod.rs b/crates/bashkit/src/zapcode_vendor/mod.rs similarity index 100% rename from crates/bashkit/src/zapcode_browser/mod.rs rename to crates/bashkit/src/zapcode_vendor/mod.rs diff --git a/crates/bashkit/src/zapcode_browser/parser/ir.rs b/crates/bashkit/src/zapcode_vendor/parser/ir.rs similarity index 100% rename from crates/bashkit/src/zapcode_browser/parser/ir.rs rename to crates/bashkit/src/zapcode_vendor/parser/ir.rs diff --git a/crates/bashkit/src/zapcode_browser/parser/mod.rs b/crates/bashkit/src/zapcode_vendor/parser/mod.rs similarity index 99% rename from crates/bashkit/src/zapcode_browser/parser/mod.rs rename to crates/bashkit/src/zapcode_vendor/parser/mod.rs index 2414a262c..eff512816 100644 --- a/crates/bashkit/src/zapcode_browser/parser/mod.rs +++ b/crates/bashkit/src/zapcode_vendor/parser/mod.rs @@ -6,7 +6,7 @@ use oxc_ast::ast; use oxc_parser::Parser; use oxc_span::SourceType; -use crate::zapcode_browser::error::{Result, ZapcodeError}; +use crate::zapcode_vendor::error::{Result, ZapcodeError}; pub fn parse(source: &str) -> Result { // Auto-wrap trailing object literals: `{ key: value }` → `({ key: value })` diff --git a/crates/bashkit/src/zapcode_browser/sandbox.rs b/crates/bashkit/src/zapcode_vendor/sandbox.rs similarity index 81% rename from crates/bashkit/src/zapcode_browser/sandbox.rs rename to crates/bashkit/src/zapcode_vendor/sandbox.rs index 4ce68c44d..546345a4f 100644 --- a/crates/bashkit/src/zapcode_browser/sandbox.rs +++ b/crates/bashkit/src/zapcode_vendor/sandbox.rs @@ -33,26 +33,26 @@ impl ResourceTracker { self.start_time = Some(crate::time::Instant::now()); } - pub fn check_time(&self, limits: &ResourceLimits) -> crate::zapcode_browser::error::Result<()> { + pub fn check_time(&self, limits: &ResourceLimits) -> crate::zapcode_vendor::error::Result<()> { if let Some(start) = self.start_time { if start.elapsed().as_millis() as u64 > limits.time_limit_ms { - return Err(crate::zapcode_browser::ZapcodeError::TimeLimitExceeded); + return Err(crate::zapcode_vendor::ZapcodeError::TimeLimitExceeded); } } Ok(()) } - pub fn check_stack(&self, limits: &ResourceLimits) -> crate::zapcode_browser::error::Result<()> { + pub fn check_stack(&self, limits: &ResourceLimits) -> crate::zapcode_vendor::error::Result<()> { if self.current_stack_depth > limits.max_stack_depth { - return Err(crate::zapcode_browser::ZapcodeError::StackOverflow(self.current_stack_depth)); + return Err(crate::zapcode_vendor::ZapcodeError::StackOverflow(self.current_stack_depth)); } Ok(()) } - pub fn track_allocation(&mut self, limits: &ResourceLimits) -> crate::zapcode_browser::error::Result<()> { + pub fn track_allocation(&mut self, limits: &ResourceLimits) -> crate::zapcode_vendor::error::Result<()> { self.allocations += 1; if self.allocations > limits.max_allocations { - return Err(crate::zapcode_browser::ZapcodeError::AllocationLimitExceeded); + return Err(crate::zapcode_vendor::ZapcodeError::AllocationLimitExceeded); } Ok(()) } diff --git a/crates/bashkit/src/zapcode_browser/snapshot.rs b/crates/bashkit/src/zapcode_vendor/snapshot.rs similarity index 92% rename from crates/bashkit/src/zapcode_browser/snapshot.rs rename to crates/bashkit/src/zapcode_vendor/snapshot.rs index ff4398724..18dba918f 100644 --- a/crates/bashkit/src/zapcode_browser/snapshot.rs +++ b/crates/bashkit/src/zapcode_vendor/snapshot.rs @@ -2,11 +2,11 @@ use std::collections::{HashMap, HashSet}; use serde::{Deserialize, Serialize}; -use crate::zapcode_browser::compiler::CompiledProgram; -use crate::zapcode_browser::error::{Result, ZapcodeError}; -use crate::zapcode_browser::sandbox::ResourceLimits; -use crate::zapcode_browser::value::Value; -use crate::zapcode_browser::vm::{CallFrame, Continuation, TryInfo, Vm, VmState}; +use crate::zapcode_vendor::compiler::CompiledProgram; +use crate::zapcode_vendor::error::{Result, ZapcodeError}; +use crate::zapcode_vendor::sandbox::ResourceLimits; +use crate::zapcode_vendor::value::Value; +use crate::zapcode_vendor::vm::{CallFrame, Continuation, TryInfo, Vm, VmState}; /// Internal serializable representation of VM state at a suspension point. #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/bashkit/src/zapcode_browser/trace.rs b/crates/bashkit/src/zapcode_vendor/trace.rs similarity index 100% rename from crates/bashkit/src/zapcode_browser/trace.rs rename to crates/bashkit/src/zapcode_vendor/trace.rs diff --git a/crates/bashkit/src/zapcode_browser/upstream-sha256.json b/crates/bashkit/src/zapcode_vendor/upstream-sha256.json similarity index 100% rename from crates/bashkit/src/zapcode_browser/upstream-sha256.json rename to crates/bashkit/src/zapcode_vendor/upstream-sha256.json diff --git a/crates/bashkit/src/zapcode_browser/value.rs b/crates/bashkit/src/zapcode_vendor/value.rs similarity index 100% rename from crates/bashkit/src/zapcode_browser/value.rs rename to crates/bashkit/src/zapcode_vendor/value.rs diff --git a/crates/bashkit/src/zapcode_browser/vm/builtins.rs b/crates/bashkit/src/zapcode_vendor/vm/builtins.rs similarity index 98% rename from crates/bashkit/src/zapcode_browser/vm/builtins.rs rename to crates/bashkit/src/zapcode_vendor/vm/builtins.rs index 3a081316f..84bae2b2c 100644 --- a/crates/bashkit/src/zapcode_browser/vm/builtins.rs +++ b/crates/bashkit/src/zapcode_vendor/vm/builtins.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use indexmap::IndexMap; -use crate::zapcode_browser::error::{Result, ZapcodeError}; -use crate::zapcode_browser::value::Value; +use crate::zapcode_vendor::error::{Result, ZapcodeError}; +use crate::zapcode_vendor::value::Value; /// Register built-in global objects and functions. pub fn register_globals(globals: &mut HashMap) { @@ -507,6 +507,8 @@ fn call_string_method(s: &Arc, method: &str, args: &[Value]) -> Result 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); } let padding: String = pad.chars().cycle().take(pad_len).collect(); Value::String(Arc::from(format!("{}{}", padding, s).as_str())) } @@ -523,6 +525,8 @@ fn call_string_method(s: &Arc, method: &str, args: &[Value]) -> Result 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); } let padding: String = pad.chars().cycle().take(pad_len).collect(); Value::String(Arc::from(format!("{}{}", s, padding).as_str())) } diff --git a/crates/bashkit/src/zapcode_browser/vm/mod.rs b/crates/bashkit/src/zapcode_vendor/vm/mod.rs similarity index 99% rename from crates/bashkit/src/zapcode_browser/vm/mod.rs rename to crates/bashkit/src/zapcode_vendor/vm/mod.rs index a51deb9dc..fdcc6bc03 100644 --- a/crates/bashkit/src/zapcode_browser/vm/mod.rs +++ b/crates/bashkit/src/zapcode_vendor/vm/mod.rs @@ -3,13 +3,13 @@ use std::sync::Arc; use indexmap::IndexMap; -use crate::zapcode_browser::compiler::instruction::{Constant, Instruction}; -use crate::zapcode_browser::compiler::CompiledProgram; -use crate::zapcode_browser::error::{Result, ZapcodeError}; -use crate::zapcode_browser::sandbox::{ResourceLimits, ResourceTracker}; -use crate::zapcode_browser::snapshot::ZapcodeSnapshot; -use crate::zapcode_browser::trace::{ExecutionTrace, SpanBuilder, TraceStatus}; -use crate::zapcode_browser::value::{Closure, FunctionId, GeneratorObject, SuspendedFrame, Value}; +use crate::zapcode_vendor::compiler::instruction::{Constant, Instruction}; +use crate::zapcode_vendor::compiler::CompiledProgram; +use crate::zapcode_vendor::error::{Result, ZapcodeError}; +use crate::zapcode_vendor::sandbox::{ResourceLimits, ResourceTracker}; +use crate::zapcode_vendor::snapshot::ZapcodeSnapshot; +use crate::zapcode_vendor::trace::{ExecutionTrace, SpanBuilder, TraceStatus}; +use crate::zapcode_vendor::value::{Closure, FunctionId, GeneratorObject, SuspendedFrame, Value}; mod builtins; @@ -2402,7 +2402,7 @@ impl Vm { } // Re-export for the ParamPattern type used in function calls -use crate::zapcode_browser::parser::ir::ParamPattern; +use crate::zapcode_vendor::parser::ir::ParamPattern; fn is_array_method(name: &str) -> bool { matches!( @@ -2505,7 +2505,7 @@ impl ZapcodeRun { // Parse let parse_span = SpanBuilder::new("parse"); - let program = match crate::zapcode_browser::parser::parse(&self.source) { + let program = match crate::zapcode_vendor::parser::parse(&self.source) { Ok(p) => { root_span.add_child(parse_span.finish_ok()); p @@ -2522,7 +2522,7 @@ impl ZapcodeRun { // Compile let compile_span = SpanBuilder::new("compile"); let ext_set: HashSet = self.external_functions.iter().cloned().collect(); - let compiled = match crate::zapcode_browser::compiler::compile_with_externals(&program, ext_set.clone()) { + let compiled = match crate::zapcode_vendor::compiler::compile_with_externals(&program, ext_set.clone()) { Ok(c) => { root_span.add_child(compile_span.finish_ok()); c diff --git a/crates/bashkit/tests/integration/threat_model_tests.rs b/crates/bashkit/tests/integration/threat_model_tests.rs index 7b01707b1..94724f421 100644 --- a/crates/bashkit/tests/integration/threat_model_tests.rs +++ b/crates/bashkit/tests/integration/threat_model_tests.rs @@ -7614,6 +7614,34 @@ mod typescript_security { assert_ne!(result.exit_code, 0, "Memory bomb should not succeed"); } + /// TM-TS-025: a huge padStart/padEnd length fails the run instead of + /// asking the allocator for ~1 TiB and aborting the host process. + #[tokio::test] + async fn threat_ts_pad_huge_length_fails_cleanly() { + let mut bash = bash_with_ts(); + for method in ["padStart", "padEnd"] { + let result = bash + .exec(&format!( + "ts -c \"console.log('a'.{method}(2 ** 40).length)\"" + )) + .await + .unwrap(); + assert_ne!(result.exit_code, 0, "{method} should fail"); + assert!( + result.stdout.is_empty(), + "{method} printed {:?}", + result.stdout + ); + } + // Ordinary padding still works, including multi-char pads. + let result = bash + .exec("ts -c \"console.log('7'.padStart(3, '0') + '|' + 'ab'.padEnd(5, 'xy'))\"") + .await + .unwrap(); + assert_eq!(result.exit_code, 0, "stderr: {}", result.stderr); + assert_eq!(result.stdout.trim(), "007|abxyx"); + } + /// TM-TS-003: TypeScript stack overflow blocked #[tokio::test] async fn threat_ts_stack_overflow() { diff --git a/knowledge/log.md b/knowledge/log.md index e43d8d872..a492d6062 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -1,5 +1,9 @@ # Bashkit Knowledge Update Log +## 2026-11-10 + +* **ZapCode vendored on every target; padStart/padEnd capped**: the pre-release check reproduced security audit F5 on main: `ts -c "'a'.padStart(2**40)"` makes zapcode-core 1.5.1 (latest on crates.io) reserve ~1 TiB, and the failed allocation aborts the process with every tenant. Native builds now use the in-tree ZapCode copy that wasm32-unknown-unknown already used (renamed `zapcode_browser` to `zapcode_vendor`), the registry `zapcode-core` dependency is gone, and the copy carries a `bashkit fork:` edit capping the pad target length at 10,000,000 like upstream `repeat`. `scripts/check_zapcode_vendor.py` now lists fork edits and fails on unlisted markers. A crates.io fork like `bashkit-monty` was not needed since the copy ships inside `bashkit`. See [ZapCode Runtime](runtimes/zapcode-runtime.md#vendored-source), [Threat Model](security/threat-model.md), TM-TS-025. + ## 2026-11-09 * **Monty upstream watch split: advisories stay daily, release drift moves to maintenance**: the daily `monty-upstream.yml` went red the moment upstream shipped 1.5.0 and stayed red until a ~9k-line fork re-sync landed, which is noise rather than signal. The *release* half is therefore a maintenance checklist item now (`just check-monty-upstream`). The *advisory* half stays on the daily schedule, via the script's existing `--no-release`: the fork crates are renamed, so cargo audit/deny and Dependabot can never match an upstream `monty` CVE by name, and this workflow is the only automated thing that would. Moving it to a quarterly pass would have stretched CVE detection from about a day to about a quarter. Advisory-only is green by default, so it has the opposite noise profile to the release check. The workflow invokes the script directly rather than the `just` recipe, which takes no arguments. See [Dependencies](operations/dependencies.md#monty-forks), [Maintenance](operations/maintenance.md). diff --git a/knowledge/operations/dependencies.md b/knowledge/operations/dependencies.md index 982676761..2dabd4b36 100644 --- a/knowledge/operations/dependencies.md +++ b/knowledge/operations/dependencies.md @@ -274,26 +274,22 @@ Remove it when `branches` compiles on nightly without `std`. ## oxc is held at 0.117.x by the vendored ZapCode parser `bashkit` declares five oxc crates (`oxc_parser`, `oxc_ast`, `oxc_allocator`, -`oxc_span`, `oxc_syntax`) for the `wasm32-unknown-unknown` TypeScript path, -where `zapcode_browser/parser` walks the oxc AST directly rather than going -through the published `zapcode-core`. The versions are chosen to match what -upstream ZapCode vendors, so the two sides of the same parser pipeline agree. - -`zapcode-core` 1.5.1 requires `oxc ^0.117`, so it does not move when bashkit's -declaration does. #2758 bumped the declaration to 0.154.0 and Cargo resolved a -**second** copy of all 13 oxc crates — `oxc_parser`, `oxc_ast` and the rest -each appearing at both 0.117.0 and 0.154.0 — putting the vendored parser and -`zapcode-core` 37 minor versions apart. Two further costs came with it: oxc -0.154 requires rustc 1.97.0 against the 1.95.0 in `rust-toolchain.toml` (the -`WASM web package` job failed at resolution, the same shape as the wasmtime -49.x failure in #2708), and it added 19 unvetted crates, including +`oxc_span`, `oxc_syntax`) for the TypeScript builtin, where the vendored +`zapcode_vendor/parser` (ZapCode 1.5.1, used on every target since the +registry `zapcode-core` dependency was dropped) walks the oxc AST directly. +The versions match what upstream ZapCode 1.5.1 was written against. + +History: while `zapcode-core` was still a native dependency it required +`oxc ^0.117`, so #2758's bump to 0.154.0 resolved a **second** copy of all 13 +oxc crates, 37 minor versions apart, needed rustc 1.97.0 against the pinned +toolchain (the `WASM web package` job failed at resolution, the same shape as +the wasmtime 49.x failure in #2708), and added 19 unvetted crates, including `compact_str` 0.10, `phf` 0.14 and `oxc_index` 5.0. -`oxc_*` is therefore in dependabot's `ignore` list outright, not by -update-type: every release past 0.117.x splits the graph the same way, so there -is no version to bump to. Lifting it waits on a `zapcode-core` release built -against a newer oxc, and then means bumping the pinned toolchain and porting -the vendored parser in one deliberate change — not inside an aggregated +`oxc_*` stays in dependabot's `ignore` list outright: any oxc release past +0.117.x changes the AST the vendored parser walks. Moving it means porting the +vendored parser (or re-vendoring a newer ZapCode release) and bumping the +pinned toolchain in one deliberate change, not inside an aggregated `chore(deps)` PR. ## Dependabot rules that keep its jobs runnable diff --git a/knowledge/runtimes/zapcode-runtime.md b/knowledge/runtimes/zapcode-runtime.md index e94e274d7..90686da7c 100644 --- a/knowledge/runtimes/zapcode-runtime.md +++ b/knowledge/runtimes/zapcode-runtime.md @@ -23,7 +23,8 @@ Experimental Sandboxed TypeScript/JavaScript execution via `typescript`, `ts`, `node`, `deno`, and `bun` builtins, powered by the [ZapCode](https://github.com/TheUncharted/zapcode) embedded TypeScript -interpreter written in Rust (`zapcode-core` on crates.io). Runs directly in +interpreter written in Rust (`zapcode-core` 1.5.1, vendored in-tree as +`crates/bashkit/src/zapcode_vendor`, see "Vendored source"). Runs directly in the host process, no subprocess, no IPC. ### Registration (Opt-in) @@ -42,7 +43,7 @@ matching the `python` pattern: `Bash::builder().typescript()`, - No filesystem/network/eval access by design (sandbox-safe) - Snapshotable execution state (<2 KB) - External function suspend/resume for VFS bridging -- Published on crates.io (`zapcode-core`) +- MIT, small enough to vendor and patch (`zapcode-core`) ### Usage @@ -197,22 +198,35 @@ a hint to `help()` and `system_prompt()`: > File I/O via readFile()/writeFile() async functions. No npm/import/require. > No HTTP/network. No eval(). -### Browser platform clocks +### Vendored source -Only wasm32-unknown-unknown uses the source copy in -`crates/bashkit/src/zapcode_browser`. ZapCode 1.5.1 uses std Instant in its resource -tracker and Instant/SystemTime in tracing, which panic on this target. The copy -replaces those reads with Bashkit's clock shim; time limits remain enabled. -Native and WASI builds retain the registry crate and its public value types. +Decision (2026-11-10): every target builds the in-tree copy of ZapCode 1.5.1 in +`crates/bashkit/src/zapcode_vendor`; the registry `zapcode-core` crate is no +longer a dependency. Two reasons: + +1. **Resource-limit fixes.** Upstream allocates unchecked in places, and an + allocation failure aborts the whole process (all tenants). Bashkit carries + those fixes as `bashkit fork:` edits. Current: `padStart`/`padEnd` reject a + target length above 10,000,000 with `AllocationLimitExceeded`, the same cap + upstream applies to `repeat` (TM-TS-025, security audit run-1 F5). +2. **Browser clocks.** ZapCode uses std Instant in its resource tracker and + Instant/SystemTime in tracing, which panic on wasm32-unknown-unknown. The + copy reads Bashkit's clock shim (`crate::time`), which is std::time on + native, so time limits stay enabled everywhere. + +A crates.io fork (like `bashkit-monty`) was not needed: ZapCode has no +dependents outside bashkit, and the copy ships inside the `bashkit` crate. Upstream is MIT, with its license retained. `upstream-sha256.json` records every -original source file. The only mechanical namespace change is `crate::` to -`crate::zapcode_browser::`, plus lib.rs to mod.rs. `scripts/check_zapcode_browser.py` -reverses those changes and the two clock substitutions, then checks hashes and -the complete file inventory and alignment with the native Cargo.lock version. Rustfmt and Clippy skip this upstream source like -the jaq-json vendor. To update, copy a reviewed crate release, regenerate hashes, -apply those changes, retain the license and rerun the real browser runtime suite. -Keep parser/postcard/indexmap dependency versions aligned with upstream. Remove -the copy once upstream provides browser-safe clocks; never disable deadlines. +original source file. Mechanical changes: `crate::` to +`crate::zapcode_vendor::`, lib.rs to mod.rs. `scripts/check_zapcode_vendor.py` +(CI) reverses those, the two clock substitutions and every listed +`bashkit fork:` edit, then checks hashes and the complete file inventory; an +unlisted marker or drifted edit fails. Rustfmt and Clippy skip this upstream +source like the jaq-json vendor. To update, copy a reviewed crate release, +regenerate hashes, re-apply the namespace/clock changes and fork edits (drop +any upstream fixed), retain the license, and rerun the TypeScript threat-model +tests and the real browser runtime suite. Keep oxc/postcard/indexmap versions +aligned with upstream. Never disable deadlines or limits in the copy. See [Browser Package](browser-package.md) for bundle and callback session rules. diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 6fe02edd8..adf3397c5 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -2229,6 +2229,7 @@ TypeScript execution requires two explicit opt-in steps, matching the Python bui | TM-TS-022 | Script reads from host filesystem | Critical | Script file loaded via VFS | `threat_ts_script_from_vfs` | | TM-TS-023 | Shebang line injection | Low | Shebang stripped safely | `threat_ts_shebang_stripped` | | TM-TS-024 | Deeply nested source overflows the native stack in ZapCode's parser/compiler and aborts the host process | Critical | Conservative nesting estimate rejects depth > 1000 before ZapCode; parse/compile run on a 128 MiB-stack thread (4x debug margin) | `deeply_nested_source_fails_cleanly`, `deep_nesting_at_the_limit_does_not_overflow`, `deep_nesting_past_the_limit_is_rejected` | +| TM-TS-025 | `'a'.padStart(2**40)` / `padEnd` asks the allocator for ~1 TiB and aborts the host process (all tenants) | High | Vendored ZapCode `bashkit fork:` edit caps the target length at 10,000,000 (same cap as `repeat`) and fails the run with `AllocationLimitExceeded` | `threat_ts_pad_huge_length_fails_cleanly` | ### Blocked Language Features diff --git a/scripts/check_zapcode_browser.py b/scripts/check_zapcode_browser.py deleted file mode 100644 index b3cc997f2..000000000 --- a/scripts/check_zapcode_browser.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python3 -"""Keep the browser VM copy byte-close to the recorded ZapCode 1.5.1 source.""" -import hashlib -import json -import tomllib -from pathlib import Path - -root = Path(__file__).resolve().parents[1] / "crates/bashkit/src/zapcode_browser" -native_versions = {package["version"] for package in tomllib.loads((root.parents[3] / "Cargo.lock").read_text())["package"] if package["name"] == "zapcode-core"} -if native_versions != {"1.5.1"}: - raise SystemExit("update the browser source copy when updating native ZapCode") -expected = json.loads((root / "upstream-sha256.json").read_text()) -actual_paths = {str(p.relative_to(root)) for p in root.rglob("*.rs")} -if actual_paths != {"mod.rs" if p == "lib.rs" else p for p in expected}: - raise SystemExit("vendored file inventory changed") -for path, digest in expected.items(): - text = (root / ("mod.rs" if path == "lib.rs" else path)).read_text() - text = text.replace("crate::zapcode_browser::", "crate::") - if path in {"sandbox.rs", "trace.rs"}: - text = text.replace("crate::time::", "std::time::") - if hashlib.sha256(text.encode()).hexdigest() != digest: - raise SystemExit(f"unrecorded ZapCode change: {path}") -print("browser ZapCode matches 1.5.1 plus namespace and platform-clock changes") diff --git a/scripts/check_zapcode_vendor.py b/scripts/check_zapcode_vendor.py new file mode 100644 index 000000000..274ffb546 --- /dev/null +++ b/scripts/check_zapcode_vendor.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Keep the vendored ZapCode copy byte-close to the recorded 1.5.1 source. + +Allowed differences, each reversed before hashing: +- namespace: `crate::` -> `crate::zapcode_vendor::`, lib.rs -> mod.rs +- platform clock: sandbox.rs/trace.rs read `crate::time::` (Bashkit's shim) +- `bashkit fork:` edits listed in FORK_EDITS (resource-limit fixes upstream + has not shipped). Every marker in the tree must be listed here. +""" +import hashlib +import json +from pathlib import Path + +root = Path(__file__).resolve().parents[1] / "crates/bashkit/src/zapcode_vendor" + +PAD_CAP = ( + " // bashkit fork: cap like `repeat`; unbounded take() aborted the host.\n" + " if target_len > 10_000_000 { return Err(ZapcodeError::AllocationLimitExceeded); }\n" +) +# (file, inserted text, number of occurrences). TM-TS-025: padStart/padEnd. +FORK_EDITS = [("vm/builtins.rs", PAD_CAP, 2)] + +expected = json.loads((root / "upstream-sha256.json").read_text()) +actual_paths = {str(p.relative_to(root)) for p in root.rglob("*.rs")} +if actual_paths != {"mod.rs" if p == "lib.rs" else p for p in expected}: + raise SystemExit("vendored file inventory changed") + +listed_markers = {} +for path, text, count in FORK_EDITS: + listed_markers[path] = listed_markers.get(path, 0) + text.count("bashkit fork:") * count + +for path, digest in expected.items(): + text = (root / ("mod.rs" if path == "lib.rs" else path)).read_text() + if text.count("bashkit fork:") != listed_markers.get(path, 0): + raise SystemExit(f"unlisted `bashkit fork:` edit in {path}") + for edit_path, inserted, count in FORK_EDITS: + if edit_path == path: + if text.count(inserted) != count: + raise SystemExit(f"fork edit drifted in {path}") + text = text.replace(inserted, "") + text = text.replace("crate::zapcode_vendor::", "crate::") + if path in {"sandbox.rs", "trace.rs"}: + text = text.replace("crate::time::", "std::time::") + if hashlib.sha256(text.encode()).hexdigest() != digest: + raise SystemExit(f"unrecorded ZapCode change: {path}") +print("vendored ZapCode matches 1.5.1 plus namespace, platform-clock and listed fork edits") diff --git a/supply-chain/config.toml b/supply-chain/config.toml index 733a62fd4..57ffdf250 100644 --- a/supply-chain/config.toml +++ b/supply-chain/config.toml @@ -2689,10 +2689,6 @@ criteria = "safe-to-deploy" version = "0.8.2" criteria = "safe-to-deploy" -[[exemptions.zapcode-core]] -version = "1.5.1" -criteria = "safe-to-deploy" - [[exemptions.zerocopy]] version = "0.8.56" criteria = "safe-to-deploy" From 727753783c549e8246e43c0b5fbf38a01412324f Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Tue, 10 Nov 2026 20:55:40 +0000 Subject: [PATCH 2/2] docs(threat-model): add TM-TS-025 to the public threat model --- crates/bashkit/docs/threat-model.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index 5605967b5..3dcd55457 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -892,9 +892,10 @@ access is bridged through Bashkit's VFS, never the host filesystem. | Script reads host filesystem (TM-TS-022) | Load a host script | Script file loaded via VFS | MITIGATED | | Shebang line injection (TM-TS-023) | `#!...` header | Shebang stripped safely | MITIGATED | | Deeply nested source aborts the host (TM-TS-024) | A few KB of `[[[...` or `1+1+...` overflows ZapCode's recursive parser/compiler | Nesting estimate rejects depth over 1000; ZapCode steps run on a 128 MiB-stack thread | MITIGATED | +| Huge `padStart`/`padEnd` aborts the host (TM-TS-025) | `'a'.padStart(2**40)` asks the allocator for ~1 TiB | Vendored ZapCode caps the target length at 10,000,000, like `repeat`; the run fails cleanly | MITIGATED | | Bash var expansion injection (TM-TS-020) | Unquoted `$VAR` expanded before TS runs | By design; use single quotes to prevent expansion | MITIGATED | -Per-threat coverage (TM-TS-001 … TM-TS-024), including error-isolation and +Per-threat coverage (TM-TS-001 … TM-TS-025), including error-isolation and exit-code propagation cases, is also exercised by the `threat_ts_*` tests. ### Request Signing & Snapshot Integrity (TM-CRY-*, TM-SNAP-*)