@enclave-vm/core 2.15.2 → 2.16.0

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/esm/worker.mjs CHANGED
@@ -592,6 +592,157 @@ function applyBinary(op, l, r) {
592
592
  }
593
593
  }
594
594
 
595
+ // libs/core/src/stack-trace.ts
596
+ var SENSITIVE_STACK_PATTERNS = [
597
+ // Unix file system paths
598
+ /\/Users\/[^/]+\/[^\s):]*/gi,
599
+ // macOS home directories
600
+ /\/home\/[^/]+\/[^\s):]*/gi,
601
+ // Linux home directories
602
+ /\/var\/[^\s):]*/gi,
603
+ // System var directories
604
+ /\/opt\/[^\s):]*/gi,
605
+ // Optional software
606
+ /\/tmp\/[^\s):]*/gi,
607
+ // Temporary files
608
+ /\/etc\/[^\s):]*/gi,
609
+ // System configuration
610
+ /\/root\/[^\s):]*/gi,
611
+ // Root home directory
612
+ /\/mnt\/[^\s):]*/gi,
613
+ // Mount points
614
+ /\/srv\/[^\s):]*/gi,
615
+ // Service data
616
+ /\/data\/[^\s):]*/gi,
617
+ // Data directories
618
+ /\/app\/[^\s):]*/gi,
619
+ // Application directories
620
+ /\/proc\/[^\s):]*/gi,
621
+ // Process information
622
+ /\/sys\/[^\s):]*/gi,
623
+ // System files
624
+ // Windows paths
625
+ /\\\\[^\s):]*/g,
626
+ // UNC paths
627
+ /[A-Z]:\\[^\s):]+/gi,
628
+ // Windows drive paths
629
+ // URL-based paths
630
+ /file:\/\/[^\s):]+/gi,
631
+ // File URLs
632
+ /webpack:\/\/[^\s):]+/gi,
633
+ // Webpack paths
634
+ /%2F[^\s):]+/gi,
635
+ // URL-encoded paths
636
+ // Package managers and node
637
+ /node_modules\/[^\s):]+/gi,
638
+ // Node modules paths
639
+ /\/nix\/store\/[^\s):]*/gi,
640
+ // Nix store paths
641
+ /\.npm\/[^\s):]*/gi,
642
+ // NPM cache
643
+ /\.yarn\/[^\s):]*/gi,
644
+ // Yarn cache
645
+ /\.pnpm\/[^\s):]*/gi,
646
+ // PNPM cache
647
+ // Container and orchestration
648
+ /\/run\/secrets\/[^\s):]*/gi,
649
+ // Docker/K8s secrets
650
+ /\/var\/run\/[^\s):]*/gi,
651
+ // Runtime directories
652
+ /\/docker\/[^\s):]*/gi,
653
+ // Docker paths
654
+ /\/containers\/[^\s):]*/gi,
655
+ // Container paths
656
+ /\/kubelet\/[^\s):]*/gi,
657
+ // Kubernetes kubelet
658
+ // CI/CD systems
659
+ /\/github\/workspace\/[^\s):]*/gi,
660
+ // GitHub Actions
661
+ /\/runner\/[^\s):]*/gi,
662
+ // GitHub/GitLab runner
663
+ /\/builds\/[^\s):]*/gi,
664
+ // CI builds
665
+ /\/workspace\/[^\s):]*/gi,
666
+ // Generic workspace
667
+ /\/pipeline\/[^\s):]*/gi,
668
+ // CI pipelines
669
+ /\/jenkins\/[^\s):]*/gi,
670
+ // Jenkins
671
+ /\/bamboo\/[^\s):]*/gi,
672
+ // Bamboo
673
+ /\/teamcity\/[^\s):]*/gi,
674
+ // TeamCity
675
+ /\/circleci\/[^\s):]*/gi,
676
+ // CircleCI
677
+ // Cloud providers
678
+ /\/aws\/[^\s):]*/gi,
679
+ // AWS paths
680
+ /\/gcloud\/[^\s):]*/gi,
681
+ // Google Cloud
682
+ /\/azure\/[^\s):]*/gi,
683
+ // Azure paths
684
+ /s3:\/\/[^\s):]+/gi,
685
+ // S3 URIs
686
+ /gs:\/\/[^\s):]+/gi,
687
+ // GCS URIs
688
+ // Secrets and credentials (patterns that might appear in paths or errors)
689
+ /[A-Z0-9]{20,}/g,
690
+ // AWS-style access keys (20+ uppercase chars)
691
+ /sk-[a-zA-Z0-9]{32,}/g,
692
+ // OpenAI/Stripe-style secret keys
693
+ /ghp_[a-zA-Z0-9]{36,}/g,
694
+ // GitHub personal access tokens
695
+ /gho_[a-zA-Z0-9]{36,}/g,
696
+ // GitHub OAuth tokens
697
+ /github_pat_[a-zA-Z0-9_]{22,}/g,
698
+ // GitHub fine-grained tokens
699
+ /xox[baprs]-[a-zA-Z0-9-]+/g,
700
+ // Slack tokens
701
+ /Bearer\s+[a-zA-Z0-9._-]+/gi,
702
+ // Bearer tokens
703
+ /Basic\s+[a-zA-Z0-9+/=]+/gi,
704
+ // Basic auth
705
+ // Internal network info
706
+ /(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
707
+ // Private IPs
708
+ /[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
709
+ // Internal hostnames
710
+ /localhost:\d+/gi,
711
+ // Localhost with port
712
+ /127\.0\.0\.1:\d+/gi,
713
+ // Loopback with port
714
+ // User information
715
+ /\/u\/[^/]+\//gi,
716
+ // User subdirectories
717
+ /~[a-z_][a-z0-9_-]*/gi,
718
+ // Unix user home shorthand
719
+ // Anything else that is still shaped like a location: an absolute path of two or more
720
+ // segments, a URL, or a script location such as `agentscript.js:3` / `index.mjs:10:5`.
721
+ /[a-z][a-z0-9+.-]*:\/\/[^\s)]+/gi,
722
+ // Other URLs (http://host/bundle.js:1:2)
723
+ /(?:\/[\w.@%+-]+){2,}\/?/g,
724
+ // Remaining absolute paths
725
+ /[\w.@-]+\.(?:[cm]?[jt]sx?|json|node|wasm)(?::\d+){1,2}/gi
726
+ // file.ext:line[:column]
727
+ ];
728
+ var FRAME_LINE = /^\s*at\s/;
729
+ var MAX_STACK_LENGTH = 16 * 1024;
730
+ var MAX_LINE_LENGTH = 1e3;
731
+ var REDACTED_FRAME = " at [REDACTED]";
732
+ function redactLine(line) {
733
+ let out = line.length > MAX_LINE_LENGTH ? `${line.slice(0, MAX_LINE_LENGTH)}\u2026` : line;
734
+ for (const pattern of SENSITIVE_STACK_PATTERNS) {
735
+ pattern.lastIndex = 0;
736
+ out = out.replace(pattern, "[REDACTED]");
737
+ }
738
+ return out;
739
+ }
740
+ function sanitizeStackTrace(stack, sanitize = true) {
741
+ if (typeof stack !== "string" || !stack || !sanitize) return stack;
742
+ const bounded = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
743
+ return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
744
+ }
745
+
595
746
  // libs/core/src/adapters/interpreter-adapter.ts
596
747
  var SAFE_GLOBALS = Object.freeze({ Math, JSON });
597
748
  var DEFAULT_MAX_STEPS = 5e6;
@@ -603,6 +754,7 @@ var InterpreterAdapter = class {
603
754
  async execute(code, context) {
604
755
  const startTime = Date.now();
605
756
  let toolCallCount = 0;
757
+ const sanitizeStacks = context.config.sanitizeStackTraces === true;
606
758
  const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
607
759
  const toolHandler = context.toolHandler ?? context.config.toolHandler;
608
760
  const __safe_callTool = async (name, args) => {
@@ -619,7 +771,7 @@ var InterpreterAdapter = class {
619
771
  try {
620
772
  program = acorn.parse(code, { ecmaVersion: "latest", sourceType: "script" });
621
773
  } catch (error) {
622
- return this.fail(error, startTime, toolCallCount, 0, "SyntaxError");
774
+ return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
623
775
  }
624
776
  const timeout = context.config.timeout;
625
777
  const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
@@ -644,6 +796,7 @@ var InterpreterAdapter = class {
644
796
  startTime,
645
797
  toolCallCount,
646
798
  interpreter.stepCount,
799
+ sanitizeStacks,
647
800
  "TimeoutError",
648
801
  "EXECUTION_TIMEOUT"
649
802
  );
@@ -655,7 +808,7 @@ var InterpreterAdapter = class {
655
808
  };
656
809
  } catch (error) {
657
810
  const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
658
- return this.fail(error, startTime, toolCallCount, interpreter.stepCount, void 0, code2);
811
+ return this.fail(error, startTime, toolCallCount, interpreter.stepCount, sanitizeStacks, void 0, code2);
659
812
  } finally {
660
813
  if (timer) clearTimeout(timer);
661
814
  if (timeoutHandle) clearTimeout(timeoutHandle);
@@ -667,12 +820,13 @@ var InterpreterAdapter = class {
667
820
  const endTime = Date.now();
668
821
  return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
669
822
  }
670
- fail(error, startTime, toolCallCount, iterationCount, name, code) {
823
+ fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
671
824
  const err = error instanceof Error ? error : new Error(String(error));
825
+ const stack = sanitizeStackTrace(err.stack, sanitizeStacks);
672
826
  const execError = {
673
827
  message: err.message,
674
828
  name: name ?? err.name,
675
- ...err.stack ? { stack: err.stack } : {},
829
+ ...stack ? { stack } : {},
676
830
  ...code ? { code } : {}
677
831
  };
678
832
  return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Host-Function Gate
3
+ *
4
+ * With `allowFunctionsInGlobals`, the host can hand the script functions through `globals`.
5
+ * Those calls cross the same boundary as `callTool()`, so they get the same treatment:
6
+ * - refused once the execution is aborted, and capped by `maxGlobalFunctionCalls`
7
+ * (the double VM also applies its operation rate limit, shared with tool calls);
8
+ * - the return value is sanitized exactly like a tool result (`sanitizeValue` with the security
9
+ * level's limits, then serialized) and re-created inside the sandbox realm, so no host object,
10
+ * function or prototype crosses; values that cannot be sanitized are refused;
11
+ * - a host error becomes a plain error (name and message only, no host stack).
12
+ *
13
+ * Which calls are gated is fail-closed: every host function reachable through `globals` (a
14
+ * function passed directly, a method of a passed object or class instance, and
15
+ * `Function.prototype.call`/`apply`/`bind`, which invoke their receiver) is gated, except the
16
+ * built-in prototype methods of the data itself ({@link isBuiltinMethod}: `Array.prototype.map`,
17
+ * iterators, `Date.prototype.toISOString`, ...), which keep working on data globals as before.
18
+ *
19
+ * The double VM applies the count and rate limit in its parent VM and uses
20
+ * {@link createHostGlobalFunctionInvoker} for the host side; the single-VM adapter uses
21
+ * {@link createGlobalFunctionGate} through the secure proxy's `callGate` hook.
22
+ *
23
+ * @packageDocumentation
24
+ */
25
+ import type { ExecutionContext } from './types';
26
+ /**
27
+ * Whether `fn` is a method of a built-in prototype (see the module description). Such calls
28
+ * operate on data and are not gated; every other host function is.
29
+ */
30
+ export declare function isBuiltinMethod(fn: unknown): boolean;
31
+ /** Default `maxGlobalFunctionCalls` is this many times `maxToolCalls`. */
32
+ export declare const DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL = 10;
33
+ /**
34
+ * Effective cap on calls into host functions for an execution.
35
+ */
36
+ export declare function resolveMaxGlobalFunctionCalls(config: {
37
+ maxToolCalls?: number;
38
+ maxGlobalFunctionCalls?: number;
39
+ }): number;
40
+ /** Error message for an exceeded `maxGlobalFunctionCalls` (shared with the double VM). */
41
+ export declare function globalFunctionLimitMessage(max: number): string;
42
+ /**
43
+ * Host side of the double VM's global-function gate.
44
+ *
45
+ * The parent VM enforces the abort check, `maxGlobalFunctionCalls` and the rate limit, then calls
46
+ * this with the host function, the receiver and the arguments. The result is a JSON envelope
47
+ * (`{ v: 1, ok: true, value }` or `{ v: 1, ok: false, error: { name, message } }`), or a Promise
48
+ * of one when the function returned a thenable; the parent VM parses it in its own realm.
49
+ */
50
+ export declare function createHostGlobalFunctionInvoker(context: ExecutionContext): (fn: unknown, thisArg: unknown, args: unknown) => string | Promise<string>;
51
+ /**
52
+ * Functions from the sandbox realm the single-VM gate uses to re-create values there.
53
+ */
54
+ export interface SandboxRealmBridge {
55
+ /** The sandbox realm's `JSON.parse` */
56
+ parseJson(json: string): unknown;
57
+ /** Wrap a host promise in a sandbox-realm promise that settles the same way */
58
+ adoptPromise(promise: Promise<unknown>): unknown;
59
+ }
60
+ /** A secure-proxy `callGate`: decides which calls are gated and runs them. */
61
+ export interface GlobalFunctionCallGate {
62
+ /** Whether a call to `target` goes through the gate */
63
+ gates(target: unknown): boolean;
64
+ /** Run a gated call; returns a sandbox-safe value */
65
+ call(target: unknown, thisArg: unknown, args: unknown[]): unknown;
66
+ }
67
+ /**
68
+ * Gate for host functions called from the single-VM sandbox (the secure proxy's `callGate`).
69
+ *
70
+ * Refuses calls once the execution is aborted or `maxGlobalFunctionCalls` is spent, sanitizes the
71
+ * return value like a tool result and re-creates it in the sandbox realm (a promise becomes a
72
+ * sandbox-realm promise), and turns host errors into safe errors.
73
+ */
74
+ export declare function createGlobalFunctionGate(context: ExecutionContext, realm: SandboxRealmBridge): GlobalFunctionCallGate;
@@ -7,6 +7,11 @@
7
7
  * - Symbol properties (can be used for prototype manipulation)
8
8
  * - Deeply nested objects (DoS via recursion)
9
9
  * - Dangerous patterns in function source
10
+ * - Host functions hidden in collections: the built-in methods of arrays, Maps and Sets
11
+ * (forEach, iteration, get) run on the raw host collection and hand its elements straight to
12
+ * the script, bypassing the global-function gate, so only plain data may live inside them
13
+ * - Opaque containers (promises, WeakMaps, iterators, generators): their contents cannot be
14
+ * validated, and their built-in methods hand those contents to the script directly
10
15
  *
11
16
  * @packageDocumentation
12
17
  */
@@ -42,9 +47,11 @@ export interface GlobalsValidationOptions {
42
47
  * @param options Validation options
43
48
  * @param path Current path for error messages
44
49
  * @param visited WeakSet to track visited objects (circular reference detection)
50
+ * @param collectionVisited Objects already validated under the collection rule
51
+ * @param inCollection Whether `value` sits inside an array, Map or Set (plain data only)
45
52
  * @throws Error if validation fails
46
53
  */
47
- export declare function validateGlobalValue(key: string, value: unknown, options?: GlobalsValidationOptions, path?: string[], visited?: WeakSet<object>): void;
54
+ export declare function validateGlobalValue(key: string, value: unknown, options?: GlobalsValidationOptions, path?: string[], visited?: WeakSet<object>, collectionVisited?: WeakSet<object>, inCollection?: boolean): void;
48
55
  /**
49
56
  * Validate all custom globals
50
57
  *
package/index.d.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  * @packageDocumentation
12
12
  */
13
13
  export { Enclave, runAgentScript } from './enclave';
14
- export type { ExecutionResult, ExecutionError, ExecutionStats, EnclaveConfig, CreateEnclaveOptions, ToolHandler, SafeRuntimeContext, ExecutionContext, SandboxAdapter, SecurityLevel, AstPreset, SecurityLevelConfig, SecureProxyLevelConfig, ReferenceSidecarOptions, WorkerPoolConfig, PartialDoubleVmConfig, } from './types';
14
+ export type { ExecutionResult, ExecutionError, ExecutionStats, EnclaveConfig, CreateEnclaveOptions, ToolHandler, SafeRuntimeContext, ExecutionContext, SandboxAdapter, SecurityLevel, AstPreset, SecurityLevelConfig, SecureProxyLevelConfig, ReferenceSidecarOptions, WorkerPoolConfig, PartialDoubleVmConfig, CallToolOptions, ToolCallResult, ToolCallErrorInfo, ToolNamespaces, NormalizedToolNamespace, } from './types';
15
15
  export { SECURITY_LEVEL_CONFIGS } from './types';
16
16
  export { ScoringGate, ScoringGateError, createScoringGate, FeatureExtractor, ScoringCache, BaseScorer, DisabledScorer, RuleBasedScorer, ExternalApiScorer, ExternalApiScorerError, DEFAULT_SCORING_CONFIG, RULE_THRESHOLDS, } from './scoring';
17
17
  export type { Scorer, ScorerType, RiskLevel, SensitiveCategory, RuleId, ExtractedFeatures, ExtractedToolCall, PatternSignals, NumericSignals, SensitiveAccess, ExtractionMeta, RiskSignal, ScoringResult, ScoringGateResult, ScoringGateConfig, ScoringCacheConfig, LocalLlmConfig, ExternalApiConfig, } from './scoring';