bashkit 0.5.0

Awesomely fast virtual sandbox with bash and file system
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
// Security tests for embedded TypeScript (ZapCode) integration.
//
// White-box tests: exploit knowledge of internals (VFS bridging, resource
// limits, external function handlers, path resolution).
//
// Black-box tests: treat ts as an opaque command and try to break out
// of the sandbox, exhaust resources, or leak information.
//
// Covers attack vectors: eval/import/require, resource exhaustion,
// VFS escape, path manipulation, error leakage, state persistence,
// and ZapCode interpreter edge cases.
//
// NOTE: TypeScript feature is opt-in. These tests verify that when enabled,
// the sandbox is robust.

#![cfg(feature = "typescript")]

use bashkit::{Bash, ExecutionLimits, TypeScriptLimits};
use std::time::Duration;

fn bash_ts() -> Bash {
    Bash::builder().typescript().build()
}

fn bash_ts_limits(limits: TypeScriptLimits) -> Bash {
    Bash::builder().typescript_with_limits(limits).build()
}

fn bash_ts_tight() -> Bash {
    bash_ts_limits(
        TypeScriptLimits::default()
            .max_duration(Duration::from_secs(3))
            .max_memory(4 * 1024 * 1024) // 4 MB
            .max_allocations(50_000)
            .max_stack_depth(100),
    )
}

// =============================================================================
// 1. BLACK-BOX: BLOCKED LANGUAGE FEATURES
//
// Try using language features that could escape the sandbox.
// =============================================================================

mod blackbox_blocked_features {
    use super::*;

    #[tokio::test]
    async fn no_eval() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"eval('console.log(\\\"hacked\\\")')\"")
            .await
            .unwrap();
        assert!(
            !r.stdout.contains("hacked"),
            "eval must not execute code, got: {}",
            r.stdout
        );
    }

    #[tokio::test]
    async fn no_function_constructor() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"const f = new Function('return 42'); console.log(f())\"")
            .await
            .unwrap();
        assert!(
            !r.stdout.contains("42") || r.exit_code != 0,
            "Function constructor must not work"
        );
    }

    #[tokio::test]
    async fn no_import() {
        let mut bash = bash_ts();
        let r = bash.exec("ts -c \"import fs from 'fs'\"").await.unwrap();
        assert_ne!(r.exit_code, 0, "import must fail");
    }

    #[tokio::test]
    async fn no_require() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"const fs = require('fs')\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0, "require must fail");
    }

    #[tokio::test]
    async fn no_dynamic_import() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"const m = await import('fs')\"")
            .await
            .unwrap();
        // Dynamic import should fail or be treated as unknown external function
        assert!(
            r.exit_code != 0 || !r.stdout.contains("readFile"),
            "dynamic import must not succeed"
        );
    }

    #[tokio::test]
    async fn no_process_global() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"console.log(process.env.HOME)\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0, "process global should not exist");
    }

    #[tokio::test]
    async fn no_deno_global() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"console.log(Deno.readTextFileSync('/etc/passwd'))\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0, "Deno global should not exist");
        assert!(
            !r.stdout.contains("root:"),
            "should not read host filesystem"
        );
    }

    #[tokio::test]
    async fn no_bun_global() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"Bun.file('/etc/passwd')\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0, "Bun global should not exist");
    }
}

// =============================================================================
// 2. BLACK-BOX: RESOURCE EXHAUSTION
//
// Try to exhaust CPU, memory, or stack via TypeScript code.
// =============================================================================

mod blackbox_resource_exhaustion {
    use super::*;

    /// TM-TS-001: Infinite loop blocked by time limit
    #[tokio::test]
    async fn threat_ts_infinite_loop() {
        let mut bash = bash_ts_tight();
        let r = bash.exec("ts -c \"while (true) {}\"").await.unwrap();
        assert_ne!(r.exit_code, 0, "infinite loop should not succeed");
    }

    /// TM-TS-002: Memory exhaustion blocked
    #[tokio::test]
    async fn threat_ts_memory_exhaustion() {
        let mut bash = bash_ts_tight();
        let r = bash
            .exec("ts -c \"const arr: number[] = []; while (true) { arr.push(1); }\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0, "memory bomb should not succeed");
    }

    /// TM-TS-003: Stack overflow blocked by depth limit
    #[tokio::test]
    async fn threat_ts_stack_overflow() {
        let mut bash = bash_ts_tight();
        let r = bash
            .exec("ts -c \"const f = (): number => f(); f()\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0, "stack overflow should not succeed");
    }

    /// TM-TS-004: Allocation bomb blocked
    #[tokio::test]
    async fn threat_ts_allocation_bomb() {
        let mut bash = bash_ts_tight();
        let r = bash
            .exec("ts -c \"for (let i = 0; i < 10000000; i++) { const x = [1,2,3]; }\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0, "allocation bomb should not succeed");
    }

    /// String bomb - exponential string growth
    #[tokio::test]
    async fn threat_ts_string_bomb() {
        let mut bash = bash_ts_tight();
        let r = bash
            .exec("ts -c \"let s = 'a'; for (let i = 0; i < 30; i++) { s = s + s; }\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0, "string bomb should be limited");
    }

    /// Generous limits should succeed for normal code
    #[tokio::test]
    async fn normal_code_within_limits() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"let sum = 0; for (let i = 0; i < 100; i++) { sum += i; } console.log(sum)\"")
            .await
            .unwrap();
        assert_eq!(r.exit_code, 0);
        assert_eq!(r.stdout.trim(), "4950");
    }
}

// =============================================================================
// 3. WHITE-BOX: VFS SECURITY
//
// Test that VFS bridging is secure and cannot escape the sandbox.
// =============================================================================

mod whitebox_vfs_security {
    use super::*;

    /// TM-TS-005: VFS reads from virtual filesystem, not host
    #[tokio::test]
    async fn threat_ts_vfs_no_real_fs() {
        let mut bash = bash_ts();
        // /etc/passwd exists on real Linux but not in VFS
        let r = bash
            .exec("ts -c \"const content = await readFile('/etc/passwd'); console.log(content)\"")
            .await
            .unwrap();
        // Should either error or return VFS content (which doesn't have real data)
        assert!(
            !r.stdout.contains("root:"),
            "must not read real /etc/passwd"
        );
    }

    /// TM-TS-006: VFS write stays in virtual filesystem
    #[tokio::test]
    async fn threat_ts_vfs_write_sandboxed() {
        let mut bash = bash_ts();
        let r = bash
            .exec(
                "ts -c \"await writeFile('/tmp/sandbox_test.txt', 'test'); await readFile('/tmp/sandbox_test.txt')\"",
            )
            .await
            .unwrap();
        assert_eq!(r.exit_code, 0);
        assert_eq!(r.stdout.trim(), "test");
    }

    /// TM-TS-007: Path traversal blocked
    #[tokio::test]
    async fn threat_ts_vfs_path_traversal() {
        let mut bash = bash_ts();
        let r = bash
            .exec(
                "ts -c \"const content = await readFile('/tmp/../../../etc/passwd'); console.log(content)\"",
            )
            .await
            .unwrap();
        assert!(
            !r.stdout.contains("root:"),
            "path traversal must not escape VFS"
        );
    }

    /// TM-TS-008: Bash/TypeScript VFS data flows correctly
    #[tokio::test]
    async fn threat_ts_vfs_bash_ts_shared() {
        let mut bash = bash_ts();
        // Write from bash, read from TypeScript
        let r = bash
            .exec("echo 'from bash' > /tmp/shared.txt\nts -c \"await readFile('/tmp/shared.txt')\"")
            .await
            .unwrap();
        assert_eq!(r.exit_code, 0);
        assert!(r.stdout.contains("from bash"));
    }

    /// TM-TS-009: File not found handled gracefully (no crash)
    #[tokio::test]
    async fn threat_ts_vfs_error_handling() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"await readFile('/no/such/file.txt')\"")
            .await
            .unwrap();
        // Should return an error string, not crash
        assert!(
            r.stdout.contains("Error") || r.exit_code != 0,
            "missing file should be handled gracefully"
        );
    }

    /// TM-TS-010: VFS mkdir sandboxed
    #[tokio::test]
    async fn threat_ts_vfs_mkdir_sandboxed() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"await mkdir('/tmp/tsdir'); await exists('/tmp/tsdir')\"")
            .await
            .unwrap();
        assert_eq!(r.exit_code, 0);
        assert_eq!(r.stdout.trim(), "true");
    }

    /// TM-TS-011: VFS operations don't escape to host /tmp
    #[tokio::test]
    async fn threat_ts_vfs_no_host_escape() {
        let mut bash = bash_ts();
        bash.exec("ts -c \"await writeFile('/tmp/ts_escape_test', 'payload')\"")
            .await
            .unwrap();
        // Verify file doesn't exist on real host (we're in VFS)
        // The bash `test -f` in BashKit also operates on VFS, so this
        // verifies the write went to VFS, not a real assertion about host fs
        let r = bash.exec("cat /tmp/ts_escape_test").await.unwrap();
        assert_eq!(r.exit_code, 0);
        assert_eq!(r.stdout.trim(), "payload");
    }
}

// =============================================================================
// 4. WHITE-BOX: ERROR HANDLING SECURITY
//
// Errors should not leak internal information.
// =============================================================================

mod whitebox_error_handling {
    use super::*;

    /// TM-TS-012: Error output goes to stderr, not stdout
    #[tokio::test]
    async fn threat_ts_error_isolation() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"throw new Error('test error')\"")
            .await
            .unwrap();
        assert_eq!(r.exit_code, 1);
        assert!(
            r.stderr.contains("Error") || r.stderr.contains("error"),
            "error should be on stderr: '{}'",
            r.stderr
        );
    }

    /// TM-TS-013: Syntax error returns non-zero exit code
    #[tokio::test]
    async fn threat_ts_syntax_error_exit() {
        let mut bash = bash_ts();
        let r = bash.exec("ts -c \"if {\"").await.unwrap();
        assert_ne!(r.exit_code, 0, "syntax error should fail");
    }

    /// TM-TS-014: Exit code propagates to bash correctly
    #[tokio::test]
    async fn threat_ts_exit_code_propagation() {
        let mut bash = bash_ts();
        // Success case
        let r = bash
            .exec("ts -c \"console.log('ok')\"\necho $?")
            .await
            .unwrap();
        assert!(r.stdout.contains("0"), "success should give exit 0");

        // Failure case
        let r = bash
            .exec("ts -c \"throw new Error()\" 2>/dev/null\necho $?")
            .await
            .unwrap();
        assert!(r.stdout.contains("1"), "error should give exit 1");
    }

    /// TM-TS-015: Empty code fails gracefully
    #[tokio::test]
    async fn threat_ts_empty_code() {
        let mut bash = bash_ts();
        let r = bash.exec("ts -c \"\"").await.unwrap();
        assert_ne!(r.exit_code, 0);
    }

    /// TM-TS-016: Pipeline error handling
    #[tokio::test]
    async fn threat_ts_pipeline_error_handling() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"throw new Error('boom')\" 2>/dev/null | cat")
            .await
            .unwrap();
        assert!(
            !r.stdout.contains("Error"),
            "error should not leak to pipeline stdout"
        );
    }

    /// TM-TS-017: Unknown options rejected
    #[tokio::test]
    async fn threat_ts_unknown_options() {
        let mut bash = bash_ts();
        let r = bash.exec("ts --unsafe-eval code").await.unwrap();
        assert_ne!(r.exit_code, 0, "unknown options should be rejected");
    }
}

// =============================================================================
// 5. WHITE-BOX: BASH INTEGRATION SECURITY
//
// Verify TypeScript integrates safely with bash features.
// =============================================================================

mod whitebox_bash_integration {
    use super::*;

    /// TM-TS-018: TypeScript respects BashKit command limits
    #[tokio::test]
    async fn threat_ts_respects_bash_limits() {
        let limits = ExecutionLimits::new().max_commands(5);
        let mut bash = Bash::builder().typescript().limits(limits).build();
        // Each ts invocation is 1 command; should succeed with generous limits
        let r = bash.exec("ts -c \"console.log('ok')\"").await.unwrap();
        assert_eq!(r.exit_code, 0);
        assert_eq!(r.stdout, "ok\n");
    }

    /// TM-TS-019: Command substitution captures only stdout
    #[tokio::test]
    async fn threat_ts_subst_captures_stdout() {
        let mut bash = bash_ts();
        let r = bash
            .exec("result=$(ts -c \"console.log(42)\")\necho $result")
            .await
            .unwrap();
        assert_eq!(r.stdout.trim(), "42");
    }

    /// TM-TS-020: Bash variable expansion before TypeScript (by design)
    #[tokio::test]
    async fn threat_ts_variable_expansion() {
        let mut bash = bash_ts();
        // Double-quoted: bash expands $VAR before passing to ts
        bash.exec("export MYVAR=injected").await.unwrap();
        let r = bash.exec("ts -c \"console.log('$MYVAR')\"").await.unwrap();
        assert_eq!(r.stdout.trim(), "injected");

        // Single-quoted: no expansion (safe)
        let r = bash.exec("ts -c 'console.log(\"$MYVAR\")'").await.unwrap();
        assert_eq!(r.stdout.trim(), "$MYVAR");
    }

    /// TM-TS-021: TypeScript cannot execute shell commands
    #[tokio::test]
    async fn threat_ts_no_shell_exec() {
        let mut bash = bash_ts();
        // No way to execute shell commands from TypeScript
        let r = bash
            .exec("ts -c \"console.log(process.env)\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0, "process.env should not exist");
        assert!(
            !r.stdout.contains("hacked"),
            "should not execute shell commands"
        );
    }

    /// TM-TS-022: Script file from VFS (not host filesystem)
    #[tokio::test]
    async fn threat_ts_script_from_vfs() {
        let mut bash = bash_ts();
        // Write a script to VFS and execute it
        bash.exec("echo 'console.log(\"from vfs\")' > /tmp/script.ts")
            .await
            .unwrap();
        let r = bash.exec("ts /tmp/script.ts").await.unwrap();
        assert_eq!(r.exit_code, 0);
        assert_eq!(r.stdout.trim(), "from vfs");
    }

    /// TM-TS-023: Shebang line stripped safely
    #[tokio::test]
    async fn threat_ts_shebang_stripped() {
        let mut bash = bash_ts();
        bash.exec("printf '#!/usr/bin/env ts\\nconsole.log(\"safe\")' > /tmp/shebang.ts")
            .await
            .unwrap();
        let r = bash.exec("ts /tmp/shebang.ts").await.unwrap();
        assert_eq!(r.exit_code, 0);
        assert_eq!(r.stdout.trim(), "safe");
    }
}

// =============================================================================
// 6. WHITE-BOX: OPT-IN VERIFICATION
//
// Verify that TypeScript is NOT available unless explicitly opted in.
// =============================================================================

mod optin_verification {
    use bashkit::{Bash, TypeScriptExtension};

    /// TypeScript commands are NOT registered by default
    #[tokio::test]
    async fn ts_not_available_by_default() {
        let mut bash = Bash::builder().build();
        let r = bash.exec("ts -c \"console.log('hi')\"").await.unwrap();
        assert_ne!(r.exit_code, 0, "ts should not be available without opt-in");
    }

    /// Node command is NOT registered by default
    #[tokio::test]
    async fn node_not_available_by_default() {
        let mut bash = Bash::builder().build();
        let r = bash.exec("node -e \"console.log('hi')\"").await.unwrap();
        assert_ne!(
            r.exit_code, 0,
            "node should not be available without opt-in"
        );
    }

    /// Deno command is NOT registered by default
    #[tokio::test]
    async fn deno_not_available_by_default() {
        let mut bash = Bash::builder().build();
        let r = bash.exec("deno -e \"console.log('hi')\"").await.unwrap();
        assert_ne!(
            r.exit_code, 0,
            "deno should not be available without opt-in"
        );
    }

    /// Bun command is NOT registered by default
    #[tokio::test]
    async fn bun_not_available_by_default() {
        let mut bash = Bash::builder().build();
        let r = bash.exec("bun -e \"console.log('hi')\"").await.unwrap();
        assert_ne!(r.exit_code, 0, "bun should not be available without opt-in");
    }

    /// TypeScript IS available after .typescript() builder call
    #[tokio::test]
    async fn ts_available_after_optin() {
        let mut bash = Bash::builder().typescript().build();
        let r = bash.exec("ts -c \"console.log('hi')\"").await.unwrap();
        assert_eq!(r.exit_code, 0, "ts should work after opt-in");
        assert_eq!(r.stdout.trim(), "hi");
    }

    /// TypeScript can be registered as an extension.
    #[tokio::test]
    async fn typescript_extension_registers_aliases() {
        let mut bash = Bash::builder()
            .extension(TypeScriptExtension::default())
            .build();

        let r = bash
            .exec("typescript -c \"console.log('ok')\"")
            .await
            .unwrap();
        assert_eq!(r.exit_code, 0);
        assert_eq!(r.stdout.trim(), "ok");
    }

    /// All aliases available after .typescript()
    #[tokio::test]
    async fn all_aliases_available_after_optin() {
        let mut bash = Bash::builder().typescript().build();
        for cmd in &["ts", "typescript", "node", "deno", "bun"] {
            let flag = if *cmd == "ts" || *cmd == "typescript" {
                "-c"
            } else {
                "-e"
            };
            let r = bash
                .exec(&format!("{cmd} {flag} \"console.log('ok')\""))
                .await
                .unwrap();
            assert_eq!(r.exit_code, 0, "{cmd} should work after opt-in");
        }
    }

    /// When compat_aliases=false, only ts/typescript are registered
    #[tokio::test]
    async fn compat_aliases_disabled() {
        use bashkit::TypeScriptConfig;
        let mut bash = Bash::builder()
            .typescript_with_config(TypeScriptConfig::default().compat_aliases(false))
            .build();

        // ts and typescript should work
        let r = bash.exec("ts -c \"console.log('ok')\"").await.unwrap();
        assert_eq!(r.exit_code, 0, "ts should work");

        let r = bash
            .exec("typescript -c \"console.log('ok')\"")
            .await
            .unwrap();
        assert_eq!(r.exit_code, 0, "typescript should work");

        // node, deno, bun should NOT be available
        for cmd in &["node", "deno", "bun"] {
            let r = bash
                .exec(&format!("{cmd} -e \"console.log('hi')\""))
                .await
                .unwrap();
            assert_ne!(
                r.exit_code, 0,
                "{cmd} should not be available with compat_aliases=false"
            );
        }
    }

    /// Unsupported mode hints show helpful text for node --inspect
    #[tokio::test]
    async fn unsupported_mode_hint_node_inspect() {
        let mut bash = Bash::builder().typescript().build();
        let r = bash.exec("node --inspect app.js").await.unwrap();
        assert_ne!(r.exit_code, 0);
        assert!(
            r.stderr.contains("hint:"),
            "should show hint text for --inspect"
        );
        assert!(
            r.stderr.contains("ZapCode"),
            "should mention ZapCode in hint"
        );
    }

    /// Unsupported mode hints show helpful text for deno subcommands
    #[tokio::test]
    async fn unsupported_mode_hint_deno_run() {
        let mut bash = Bash::builder().typescript().build();
        let r = bash.exec("deno run script.ts").await.unwrap();
        assert_ne!(r.exit_code, 0);
        assert!(r.stderr.contains("hint:"));
    }

    /// Unsupported mode hints show helpful text for bun subcommands
    #[tokio::test]
    async fn unsupported_mode_hint_bun_install() {
        let mut bash = Bash::builder().typescript().build();
        let r = bash.exec("bun install").await.unwrap();
        assert_ne!(r.exit_code, 0);
        assert!(r.stderr.contains("hint:"));
    }

    /// Hints can be disabled via config
    #[tokio::test]
    async fn unsupported_mode_hint_disabled() {
        use bashkit::TypeScriptConfig;
        let mut bash = Bash::builder()
            .typescript_with_config(TypeScriptConfig::default().unsupported_mode_hint(false))
            .build();
        let r = bash.exec("node --inspect app.js").await.unwrap();
        assert_ne!(r.exit_code, 0);
        assert!(
            !r.stderr.contains("hint:"),
            "should NOT show hint when disabled"
        );
    }
}

// =============================================================================
// 7. PROTOTYPE POLLUTION / OBJECT MANIPULATION
//
// Attempt to abuse JavaScript's dynamic features.
// =============================================================================

mod prototype_attacks {
    use super::*;

    /// Try __proto__ manipulation
    #[tokio::test]
    async fn no_proto_pollution() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"const obj: any = {}; obj.__proto__.polluted = true; console.log(({} as any).polluted)\"")
            .await
            .unwrap();
        // Should either fail or print undefined (not "true")
        assert!(
            !r.stdout.contains("true"),
            "__proto__ pollution should not work"
        );
    }

    /// Try constructor manipulation
    #[tokio::test]
    async fn no_constructor_abuse() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"const obj: any = {}; obj.constructor.constructor('return this')()\"")
            .await
            .unwrap();
        // Should fail — no Function constructor escape
        assert!(
            r.exit_code != 0 || !r.stdout.contains("[object"),
            "constructor abuse should not work"
        );
    }

    /// Try globalThis access
    #[tokio::test]
    async fn no_globalthis_escape() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"const keys = Object.keys(globalThis); console.log(keys.length)\"")
            .await
            .unwrap();
        // globalThis might work but should only expose safe builtins
        // The important thing is no process/require/Deno/Bun on it
        if r.exit_code == 0 {
            assert!(
                !r.stdout.contains("process") && !r.stdout.contains("require"),
                "globalThis should not expose dangerous globals"
            );
        }
    }
}

// =============================================================================
// 8. CUSTOM LIMITS TESTS
//
// Verify that custom limits are actually enforced.
// =============================================================================

mod custom_limits {
    use super::*;

    /// Very tight time limit stops long computation
    #[tokio::test]
    async fn tight_time_limit() {
        let mut bash =
            bash_ts_limits(TypeScriptLimits::default().max_duration(Duration::from_millis(100)));
        let r = bash
            .exec("ts -c \"let i = 0; while (true) { i++; }\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0);
    }

    /// Very tight stack depth limit
    #[tokio::test]
    async fn tight_stack_limit() {
        let mut bash = bash_ts_limits(TypeScriptLimits::default().max_stack_depth(10));
        let r = bash
            .exec("ts -c \"const f = (n: number): number => n <= 0 ? 0 : f(n - 1); f(100)\"")
            .await
            .unwrap();
        assert_ne!(r.exit_code, 0);
    }

    /// Default limits allow normal programs
    #[tokio::test]
    async fn default_limits_normal_code() {
        let mut bash = bash_ts();
        let r = bash
            .exec("ts -c \"let sum = 0; for (let i = 0; i < 100; i++) { sum += i; } console.log(sum)\"")
            .await
            .unwrap();
        assert_eq!(r.exit_code, 0);
        assert_eq!(r.stdout.trim(), "4950");
    }
}