bext-plugin-quickjs 0.2.0

QuickJS sandbox for bext — lightweight JavaScript plugin execution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! JS API surface exposed to QuickJS plugins.
//!
//! Registers `console.*` and `bext.*` globals that bridge to the host's
//! sandbox infrastructure (storage, fetch, config, metrics).

use bext_plugin_api::types::SandboxPermissions;
use rquickjs::{Ctx, Function, Object, Result as JsResult};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

/// Shared host state accessible from JS callbacks.
pub(crate) struct HostBridge {
    pub plugin_id: String,
    pub permissions: SandboxPermissions,
    pub storage_dir: PathBuf,
    pub config: serde_json::Value,
    pub fetch_limiter: Mutex<FetchLimiter>,
    pub storage_bytes: Mutex<u64>,
}

pub(crate) struct FetchLimiter {
    tokens: u32,
    max_tokens: u32,
    last_refill: std::time::Instant,
}

impl FetchLimiter {
    pub fn new(max_per_minute: u32) -> Self {
        Self {
            tokens: max_per_minute,
            max_tokens: max_per_minute,
            last_refill: std::time::Instant::now(),
        }
    }

    pub fn try_acquire(&mut self) -> bool {
        let elapsed = self.last_refill.elapsed();
        if elapsed >= std::time::Duration::from_secs(60) {
            self.tokens = self.max_tokens;
            self.last_refill = std::time::Instant::now();
        }
        if self.tokens > 0 {
            self.tokens -= 1;
            true
        } else {
            false
        }
    }
}

impl HostBridge {
    pub fn new(
        plugin_id: String,
        permissions: SandboxPermissions,
        storage_root: &std::path::Path,
        config: serde_json::Value,
    ) -> Self {
        let storage_dir = storage_root.join(&plugin_id);
        Self {
            plugin_id,
            permissions: permissions.clone(),
            storage_dir,
            config,
            fetch_limiter: Mutex::new(FetchLimiter::new(permissions.max_fetch_per_minute)),
            storage_bytes: Mutex::new(0),
        }
    }

    fn is_url_allowed(&self, url: &str) -> bool {
        if self.permissions.allowed_urls.is_empty() {
            return false;
        }
        self.permissions
            .allowed_urls
            .iter()
            .any(|p| glob_match(p, url))
    }

    fn try_fetch(&self) -> bool {
        self.fetch_limiter
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .try_acquire()
    }

    fn check_storage_quota(&self, additional: u64) -> bool {
        let current = self.storage_bytes.lock().unwrap_or_else(|e| e.into_inner());
        *current + additional <= self.permissions.storage_quota_kb * 1024
    }

    fn record_storage(&self, bytes: u64) {
        let mut current = self.storage_bytes.lock().unwrap_or_else(|e| e.into_inner());
        *current += bytes;
    }

    fn sanitize_key(key: &str) -> Option<&str> {
        if key.contains("..") || key.contains('/') || key.contains('\\') || key.contains('\0') {
            None
        } else {
            Some(key)
        }
    }
}

/// Register `console` and `bext` globals on the given JS context.
pub(crate) fn register_globals(ctx: &Ctx<'_>, bridge: Arc<HostBridge>) -> JsResult<()> {
    let globals = ctx.globals();

    // ── console.* ─────────────────────────────────────────────────
    let console = Object::new(ctx.clone())?;
    {
        let id = bridge.plugin_id.clone();
        console.set(
            "log",
            Function::new(ctx.clone(), move |msg: String| {
                tracing::info!(plugin = %id, "{}", msg);
            }),
        )?;
    }
    {
        let id = bridge.plugin_id.clone();
        console.set(
            "warn",
            Function::new(ctx.clone(), move |msg: String| {
                tracing::warn!(plugin = %id, "{}", msg);
            }),
        )?;
    }
    {
        let id = bridge.plugin_id.clone();
        console.set(
            "error",
            Function::new(ctx.clone(), move |msg: String| {
                tracing::error!(plugin = %id, "{}", msg);
            }),
        )?;
    }
    {
        let id = bridge.plugin_id.clone();
        console.set(
            "info",
            Function::new(ctx.clone(), move |msg: String| {
                tracing::info!(plugin = %id, "{}", msg);
            }),
        )?;
    }
    {
        let id = bridge.plugin_id.clone();
        console.set(
            "debug",
            Function::new(ctx.clone(), move |msg: String| {
                tracing::debug!(plugin = %id, "{}", msg);
            }),
        )?;
    }
    globals.set("console", console)?;

    // ── bext.* ────────────────────────────────────────────────────
    let bext = Object::new(ctx.clone())?;

    // bext.config — read-only config object
    {
        let config_str = bridge.config.to_string();
        let config_val: rquickjs::Value = ctx.json_parse(config_str)?;
        bext.set("config", config_val)?;
    }

    // bext.storage.get/set/delete
    let storage = Object::new(ctx.clone())?;
    {
        let b = bridge.clone();
        storage.set(
            "get",
            Function::new(
                ctx.clone(),
                move |key: String| -> rquickjs::Result<Option<String>> {
                    let key = HostBridge::sanitize_key(&key).ok_or_else(|| {
                        rquickjs::Error::new_from_js("string", "invalid storage key")
                    })?;
                    let path = b.storage_dir.join(key);
                    match std::fs::read_to_string(&path) {
                        Ok(val) => Ok(Some(val)),
                        Err(_) => Ok(None),
                    }
                },
            ),
        )?;
    }
    {
        let b = bridge.clone();
        storage.set(
            "set",
            Function::new(
                ctx.clone(),
                move |key: String, value: String| -> rquickjs::Result<bool> {
                    let key = HostBridge::sanitize_key(&key).ok_or_else(|| {
                        rquickjs::Error::new_from_js("string", "invalid storage key")
                    })?;
                    let bytes = value.len() as u64;
                    if !b.check_storage_quota(bytes) {
                        return Ok(false);
                    }
                    let _ = std::fs::create_dir_all(&b.storage_dir);
                    match std::fs::write(b.storage_dir.join(key), value.as_bytes()) {
                        Ok(()) => {
                            b.record_storage(bytes);
                            Ok(true)
                        }
                        Err(_) => Ok(false),
                    }
                },
            ),
        )?;
    }
    {
        let b = bridge.clone();
        storage.set(
            "delete",
            Function::new(ctx.clone(), move |key: String| -> rquickjs::Result<bool> {
                let key = HostBridge::sanitize_key(&key)
                    .ok_or_else(|| rquickjs::Error::new_from_js("string", "invalid storage key"))?;
                Ok(std::fs::remove_file(b.storage_dir.join(key)).is_ok())
            }),
        )?;
    }
    bext.set("storage", storage)?;

    // bext.fetch(url, options?) — blocking HTTP fetch
    // Returns a JSON string `{"status":200,"body":"..."}` to avoid rquickjs lifetime issues.
    // Parse in JS: `let resp = JSON.parse(bext.fetch(url, opts))`
    {
        /// Maximum response body size (1 MB).
        const MAX_RESPONSE_BYTES: u64 = 1_048_576;

        let b = bridge.clone();
        bext.set("fetch", Function::new(ctx.clone(), move |url: String, method: Option<String>, body: Option<String>| -> rquickjs::Result<String> {
            // SSRF prevention: block private/internal IPs
            if is_private_url(&url) {
                return Err(rquickjs::Error::new_from_js("string", "blocked: private/internal URL"));
            }
            // URL allowlist check
            if !b.is_url_allowed(&url) {
                return Err(rquickjs::Error::new_from_js("string", "URL not in allowlist"));
            }
            // Rate limit
            if !b.try_fetch() {
                return Err(rquickjs::Error::new_from_js("string", "rate limit exceeded"));
            }

            let method = method.unwrap_or_else(|| "GET".into());

            let request = match method.to_uppercase().as_str() {
                "GET" => ureq::get(&url),
                "POST" => ureq::post(&url),
                "PUT" => ureq::put(&url),
                "DELETE" => ureq::delete(&url),
                "PATCH" => ureq::patch(&url),
                "HEAD" => ureq::head(&url),
                _ => return Err(rquickjs::Error::new_from_js("string", "unsupported method")),
            }
            .timeout(std::time::Duration::from_secs(5));

            let response = if let Some(ref b) = body {
                request.send_string(b)
            } else {
                request.call()
            };

            let read_body_limited = |resp: ureq::Response| -> std::result::Result<String, String> {
                use std::io::Read;
                let mut reader = resp.into_reader().take(MAX_RESPONSE_BYTES + 1);
                let mut buf = Vec::new();
                match reader.read_to_end(&mut buf) {
                    Ok(_) => {
                        if buf.len() as u64 > MAX_RESPONSE_BYTES {
                            return Err(format!(
                                "response body exceeds {} byte limit",
                                MAX_RESPONSE_BYTES
                            ));
                        }
                        Ok(String::from_utf8(buf)
                            .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).to_string()))
                    }
                    Err(_) => Ok(String::new()),
                }
            };

            match response {
                Ok(resp) => {
                    let status = resp.status();
                    let resp_body = match read_body_limited(resp) {
                        Ok(body) => body,
                        Err(e) => {
                            tracing::warn!(error = %e, "fetch response body error");
                            return Err(rquickjs::Error::new_from_js("string", "response body too large or unreadable"));
                        }
                    };
                    Ok(serde_json::json!({"status": status, "body": resp_body}).to_string())
                }
                Err(ureq::Error::Status(code, resp)) => {
                    let resp_body = match read_body_limited(resp) {
                        Ok(body) => body,
                        Err(e) => {
                            tracing::warn!(error = %e, "fetch response body error");
                            return Err(rquickjs::Error::new_from_js("string", "response body too large or unreadable"));
                        }
                    };
                    Ok(serde_json::json!({"status": code, "body": resp_body}).to_string())
                }
                Err(e) => {
                    tracing::warn!(plugin = %b.plugin_id, url = %url, error = %e, "fetch failed");
                    Err(rquickjs::Error::new_from_js("string", "fetch request failed"))
                }
            }
        }))?;
    }

    // bext._metricImpl(name, value, tags) — internal, always receives 3 args
    {
        let b = bridge.clone();
        bext.set(
            "_metricImpl",
            Function::new(
                ctx.clone(),
                move |name: String, value: f64, tags: String| {
                    tracing::info!(
                        target: "bext::plugin_metric",
                        plugin = %b.plugin_id,
                        metric = %name,
                        value = value,
                        tags = %tags,
                        "plugin_metric"
                    );
                },
            ),
        )?;
    }

    globals.set("bext", bext)?;

    // bext.metric(name, value, tags?) — JS wrapper that defaults tags to "{}"
    // Must run after `bext` is attached to globals.
    ctx.eval::<(), _>(
        b"bext.metric = function(name, value, tags) { bext._metricImpl(name, value, tags || '{}'); };"
    )?;

    Ok(())
}

fn glob_match(pattern: &str, input: &str) -> bool {
    let parts: Vec<&str> = pattern.split('*').collect();
    if parts.len() == 1 {
        return pattern == input;
    }
    let mut pos = 0;
    if !parts[0].is_empty() {
        if !input.starts_with(parts[0]) {
            return false;
        }
        pos = parts[0].len();
    }
    for part in &parts[1..parts.len() - 1] {
        if part.is_empty() {
            continue;
        }
        match input[pos..].find(part) {
            Some(idx) => pos += idx + part.len(),
            None => return false,
        }
    }
    let last = parts[parts.len() - 1];
    if !last.is_empty() {
        input[pos..].ends_with(last)
    } else {
        true
    }
}

/// Check if a URL targets a private/internal IP address (SSRF prevention).
///
/// Blocks loopback (127.0.0.0/8, ::1), private ranges (10/8, 172.16/12, 192.168/16),
/// link-local (169.254/16, fe80::/10), unique-local IPv6 (fc00::/7), and
/// IPv4-mapped IPv6 addresses that resolve to private IPs.
///
/// **TOCTOU note**: There is an inherent time-of-check/time-of-use gap between
/// DNS resolution here and the subsequent HTTP request (which resolves DNS
/// again). A malicious DNS server could return a public IP on the first lookup
/// and a private IP on the second (DNS rebinding). To mitigate this, we resolve
/// ALL returned A/AAAA records and reject if ANY is private. This narrows the
/// window but does not fully eliminate it. For complete protection, the HTTP
/// client should be configured to connect to the resolved IP directly.
fn is_private_url(url_str: &str) -> bool {
    let parsed = match url::Url::parse(url_str) {
        Ok(u) => u,
        Err(_) => return true, // Unparseable → blocked
    };
    let host = match parsed.host_str() {
        Some(h) => h,
        None => return true,
    };

    // Block "localhost" variants
    let host_lower = host.to_lowercase();
    if host_lower == "localhost" || host_lower.ends_with(".localhost") {
        return true;
    }

    // Try parsing as IP directly
    if let Ok(ip) = host.parse::<std::net::IpAddr>() {
        return is_private_ip(ip);
    }

    // Strip IPv6 brackets
    let stripped = host.trim_start_matches('[').trim_end_matches(']');
    if let Ok(ip) = stripped.parse::<std::net::IpAddr>() {
        return is_private_ip(ip);
    }

    // DNS resolution — resolve hostname and check ALL returned IPs.
    // We collect all addresses to ensure we check every record, not just the first.
    // If ANY resolved address is private, the URL is blocked.
    if let Ok(addrs) = std::net::ToSocketAddrs::to_socket_addrs(&(host, 80)) {
        let all_addrs: Vec<_> = addrs.collect();
        // If DNS returned no records, block the request (suspicious)
        if all_addrs.is_empty() {
            return true;
        }
        for addr in &all_addrs {
            if is_private_ip(addr.ip()) {
                return true;
            }
        }
    }

    false
}

fn is_private_ip(ip: std::net::IpAddr) -> bool {
    match ip {
        std::net::IpAddr::V4(v4) => {
            v4.is_loopback()
                || v4.is_private()
                || v4.is_link_local()
                || v4.is_unspecified()
                || v4.is_broadcast()
        }
        std::net::IpAddr::V6(v6) => {
            v6.is_loopback()
                || v6.is_unspecified()
                || (v6.octets()[0] == 0xfe && (v6.octets()[1] & 0xc0) == 0x80) // fe80::/10 link-local
                || (v6.octets()[0] & 0xfe == 0xfc) // fc00::/7 unique-local
                || v6.to_ipv4_mapped().is_some_and(|v4| {
                    v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_unspecified()
                })
        }
    }
}