@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/node-vm.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Node.js `vm` availability check
3
+ *
4
+ * The built-in adapters need `node:vm`. Bundled for a browser or an edge runtime, `vm` is often
5
+ * mapped to an empty module, and the first call into it fails with an opaque
6
+ * `TypeError: (void 0) is not a function`; this check names the problem and the way out.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ /**
11
+ * Throw a descriptive error when this runtime does not provide `node:vm`.
12
+ */
13
+ export declare function assertNodeVmAvailable(): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.15.2",
3
+ "version": "2.16.0",
4
4
  "description": "Sandbox runtime for secure JavaScript code execution",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
@@ -44,8 +44,8 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@babel/standalone": "^7.29.0",
47
- "@enclave-vm/ast": "2.15.2",
48
- "@enclave-vm/types": "2.15.2",
47
+ "@enclave-vm/ast": "2.16.0",
48
+ "@enclave-vm/types": "2.16.0",
49
49
  "@types/estree": "1.0.8",
50
50
  "acorn": "8.15.0",
51
51
  "acorn-walk": "8.3.4",
package/safe-error.d.ts CHANGED
@@ -13,6 +13,10 @@
13
13
  /**
14
14
  * Create an Error instance whose prototype chain is severed (actual [[Prototype]]),
15
15
  * preventing prototype-chain escape to host constructors.
16
+ *
17
+ * @param message Error message
18
+ * @param name Error name
19
+ * @param code Optional error code (a read-only own property)
16
20
  */
17
- export declare function createSafeError(message: string, name?: string): Error;
21
+ export declare function createSafeError(message: string, name?: string, code?: string): Error;
18
22
  export declare function createSafeTypeError(message: string): Error;
package/safe-runtime.d.ts CHANGED
@@ -6,7 +6,8 @@
6
6
  *
7
7
  * @packageDocumentation
8
8
  */
9
- import type { ExecutionContext, SecureProxyLevelConfig } from './types';
9
+ import type { CallToolOptions, ExecutionContext, SecureProxyLevelConfig } from './types';
10
+ import type { GlobalFunctionCallGate } from './global-function-gate';
10
11
  import { ReferenceSidecar } from './sidecar/reference-sidecar';
11
12
  import { ReferenceConfig } from './sidecar/reference-config';
12
13
  import { MemoryTracker } from './memory-tracker';
@@ -35,6 +36,12 @@ export interface SafeRuntimeOptions {
35
36
  * and enforce memory limits
36
37
  */
37
38
  memoryTracker?: MemoryTracker;
39
+ /**
40
+ * Gate for calls into host functions passed in `globals` (see `createGlobalFunctionGate`).
41
+ * When provided, the custom globals are wrapped so every call into one of their functions goes
42
+ * through it.
43
+ */
44
+ globalFunctionGate?: GlobalFunctionCallGate;
38
45
  }
39
46
  /**
40
47
  * Create safe runtime context with all __safe_* functions
@@ -51,7 +58,7 @@ export declare function createSafeRuntime(context: ExecutionContext, options?: S
51
58
  isFinite: typeof isFinite;
52
59
  parseInt: typeof parseInt;
53
60
  parseFloat: typeof parseFloat;
54
- __safe_callTool: (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
61
+ __safe_callTool: (toolName: string, args: Record<string, unknown>, options?: CallToolOptions) => Promise<unknown>;
55
62
  __safe_forOf: <T>(iterable: Iterable<T>) => Iterable<T>;
56
63
  __safe_for: (init: () => void, test: () => boolean, update: () => void, body: () => void) => void;
57
64
  __safe_while: (test: () => boolean, body: () => void) => void;
@@ -67,6 +74,10 @@ export declare function createSafeRuntime(context: ExecutionContext, options?: S
67
74
  * Serialize safe runtime code as a string for injection
68
75
  * This is used by sandbox adapters that need to inject the runtime as code
69
76
  *
77
+ * The adapter provides `__internal_callTool(toolName, args, options)`; `options` is the script's
78
+ * third `callTool` argument, so the adapter implements `{ throwOnError: false }` (a failure of the
79
+ * tool resolves to `{ success: false, error }`, a success to `{ success: true, data }`).
80
+ *
70
81
  * @returns JavaScript code string containing the safe runtime
71
82
  */
72
83
  export declare function serializeSafeRuntime(): string;
package/secure-proxy.d.ts CHANGED
@@ -142,6 +142,18 @@ export interface SecureProxyOptions {
142
142
  * - Explicitly set `throwOnBlocked: false` in options
143
143
  */
144
144
  throwOnBlocked?: boolean;
145
+ /**
146
+ * Gate for calls into wrapped functions (used for host functions passed in `globals`).
147
+ *
148
+ * When set, a call through this proxy, or through any proxy derived from it (a method read off
149
+ * a wrapped object), whose target `gates()` accepts is handed to `call(target, thisArg, args)`
150
+ * instead of being invoked directly, and its return value is returned unwrapped: the gate is
151
+ * responsible for producing a sandbox-safe value. Calling such a function with `new` is refused.
152
+ */
153
+ callGate?: {
154
+ gates(target: unknown): boolean;
155
+ call(target: unknown, thisArg: unknown, args: unknown[]): unknown;
156
+ };
145
157
  }
146
158
  /**
147
159
  * Create a secure proxy that blocks dangerous property access
@@ -173,6 +185,13 @@ export declare function createSecureStandardLibrary(options?: SecureProxyOptions
173
185
  * @returns true if the object is wrapped in a secure proxy
174
186
  */
175
187
  export declare function isSecureProxy(obj: unknown): boolean;
188
+ /**
189
+ * The object a secure proxy wraps, or `value` itself when it is not one.
190
+ *
191
+ * For host code that must read a sandbox value's internal slots, which a proxy does not carry
192
+ * (a proxied Date fails `Date.prototype.getTime`). Never hand the result back to the sandbox.
193
+ */
194
+ export declare function unwrapSecureProxy<T>(value: T): T;
176
195
  /**
177
196
  * Clear the proxy cache
178
197
  *
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/core",
3
- "version": "2.15.2",
3
+ "version": "2.16.0",
4
4
  "description": "Sandbox runtime for secure JavaScript code execution",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
@@ -46,8 +46,8 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@babel/standalone": "^7.29.0",
49
- "@enclave-vm/ast": "2.15.2",
50
- "@enclave-vm/types": "2.15.2",
49
+ "@enclave-vm/ast": "2.16.0",
50
+ "@enclave-vm/types": "2.16.0",
51
51
  "@types/estree": "1.0.8",
52
52
  "acorn": "8.15.0",
53
53
  "acorn-walk": "8.3.4",
@@ -128,6 +128,9 @@ function safeSerialize(value) {
128
128
  return val;
129
129
  });
130
130
  }
131
+ function isDangerousKey(key) {
132
+ return DANGEROUS_KEYS.has(key);
133
+ }
131
134
  function sanitizeObject(value, depth = 0) {
132
135
  if (depth > MAX_DEPTH) {
133
136
  return void 0;
@@ -150,6 +153,269 @@ function sanitizeObject(value, depth = 0) {
150
153
  return result;
151
154
  }
152
155
 
156
+ // libs/core/src/adapters/worker-pool/result-encoding.ts
157
+ function encodeResult(value) {
158
+ const specialValues = [];
159
+ return { value: encodeValue(value, [], specialValues), specialValues };
160
+ }
161
+ function encodeValue(value, path, specialValues) {
162
+ if (value === void 0) {
163
+ specialValues.push({ path, kind: "undefined" });
164
+ return null;
165
+ }
166
+ if (typeof value === "number" && !Number.isFinite(value)) {
167
+ const kind = Number.isNaN(value) ? "nan" : value > 0 ? "infinity" : "-infinity";
168
+ specialValues.push({ path, kind });
169
+ return null;
170
+ }
171
+ if (value instanceof Date) {
172
+ const time = value.getTime();
173
+ specialValues.push({ path, kind: "date", time: Number.isNaN(time) ? null : time });
174
+ return null;
175
+ }
176
+ if (Array.isArray(value)) {
177
+ return value.map((item, index) => encodeValue(item, [...path, index], specialValues));
178
+ }
179
+ if (value !== null && typeof value === "object") {
180
+ const encoded = /* @__PURE__ */ Object.create(null);
181
+ for (const key of Object.keys(value)) {
182
+ if (isDangerousKey(key)) continue;
183
+ encoded[key] = encodeValue(value[key], [...path, key], specialValues);
184
+ }
185
+ return encoded;
186
+ }
187
+ return value;
188
+ }
189
+
190
+ // libs/core/src/value-sanitizer.ts
191
+ var DANGEROUS_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
192
+ var ReflectApply = Reflect.apply;
193
+ var ReflectGet2 = Reflect.get;
194
+ var ArrayIsArray2 = Array.isArray;
195
+ var ObjectKeys = Object.keys;
196
+ var ObjectCreate = Object.create;
197
+ var ObjectGetPrototypeOf = Object.getPrototypeOf;
198
+ var NumberIsFinite2 = Number.isFinite;
199
+ var MathFloor2 = Math.floor;
200
+ var MapProtoEntries = Map.prototype.entries;
201
+ var SetProtoValues = Set.prototype.values;
202
+ var DateProtoGetTime = Date.prototype.getTime;
203
+ var DateProtoToISOString = Date.prototype.toISOString;
204
+ var RegExpProtoSourceGetter = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get;
205
+ var RegExpFlagGetters = [
206
+ ["d", "hasIndices"],
207
+ ["g", "global"],
208
+ ["i", "ignoreCase"],
209
+ ["m", "multiline"],
210
+ ["s", "dotAll"],
211
+ ["u", "unicode"],
212
+ ["v", "unicodeSets"],
213
+ ["y", "sticky"]
214
+ ].map(([flag, property]) => [flag, Object.getOwnPropertyDescriptor(RegExp.prototype, property)?.get]);
215
+ var MapProtoSizeGetter = Object.getOwnPropertyDescriptor(Map.prototype, "size")?.get;
216
+ var SetProtoSizeGetter = Object.getOwnPropertyDescriptor(Set.prototype, "size")?.get;
217
+ function hasBrand(builtin, value) {
218
+ if (!builtin) return false;
219
+ try {
220
+ ReflectApply(builtin, value, []);
221
+ return true;
222
+ } catch {
223
+ return false;
224
+ }
225
+ }
226
+ function regExpToString(value) {
227
+ let flags = "";
228
+ for (const [flag, getter] of RegExpFlagGetters) {
229
+ if (getter && ReflectApply(getter, value, [])) flags += flag;
230
+ }
231
+ return `/${ReflectApply(RegExpProtoSourceGetter, value, [])}/${flags}`;
232
+ }
233
+ function isPlainObject(value) {
234
+ const prototype = ObjectGetPrototypeOf(value);
235
+ return prototype === null || ObjectGetPrototypeOf(prototype) === null;
236
+ }
237
+ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
238
+ const maxDepth = options.maxDepth ?? 20;
239
+ const maxProperties = options.maxProperties ?? 1e4;
240
+ const allowDates = options.allowDates ?? true;
241
+ const allowErrors = options.allowErrors ?? true;
242
+ if (depth > maxDepth) {
243
+ throw new Error(
244
+ `Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
245
+ );
246
+ }
247
+ if (context.propCount.count > maxProperties) {
248
+ throw new Error(
249
+ `Tool handler return value exceeds maximum properties (${maxProperties}). This limit prevents memory exhaustion from large object graphs.`
250
+ );
251
+ }
252
+ if (value === null || value === void 0) {
253
+ return value;
254
+ }
255
+ const type = typeof value;
256
+ if (type === "string" || type === "number" || type === "boolean") {
257
+ return value;
258
+ }
259
+ if (type === "bigint") {
260
+ return String(value);
261
+ }
262
+ if (type === "function") {
263
+ throw new Error(
264
+ "Tool handler returned a function. Functions cannot be returned to sandbox code as they could be used for code injection or host scope access."
265
+ );
266
+ }
267
+ if (type === "symbol") {
268
+ throw new Error(
269
+ "Tool handler returned a symbol. Symbols cannot be returned to sandbox code as they could be used for prototype manipulation."
270
+ );
271
+ }
272
+ if (type === "object" && value !== null) {
273
+ if (context.visited.has(value)) {
274
+ return "[Circular]";
275
+ }
276
+ context.visited.add(value);
277
+ }
278
+ if (ArrayIsArray2(value)) {
279
+ const rawLen = ReflectGet2(value, "length");
280
+ const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
281
+ context.propCount.count += len;
282
+ if (context.propCount.count > maxProperties) {
283
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
284
+ }
285
+ const result = [];
286
+ for (let i = 0; i < len; i++) {
287
+ let item;
288
+ try {
289
+ item = ReflectGet2(value, i);
290
+ } catch {
291
+ item = void 0;
292
+ }
293
+ result[i] = sanitizeValue(item, options, depth + 1, context);
294
+ }
295
+ return result;
296
+ }
297
+ const inspected = options.unwrap ? options.unwrap(value) : value;
298
+ const isPlain = isPlainObject(inspected);
299
+ if (!isPlain && hasBrand(DateProtoGetTime, inspected)) {
300
+ const time = ReflectApply(DateProtoGetTime, inspected, []);
301
+ if (allowDates) {
302
+ return new Date(time);
303
+ }
304
+ return ReflectApply(DateProtoToISOString, inspected, []);
305
+ }
306
+ if (value instanceof Error) {
307
+ const rawName = ReflectGet2(value, "name");
308
+ const rawMessage = ReflectGet2(value, "message");
309
+ const name = typeof rawName === "string" ? rawName : "Error";
310
+ const message = typeof rawMessage === "string" ? rawMessage : "";
311
+ if (allowErrors) {
312
+ return {
313
+ name,
314
+ message
315
+ // Do NOT include stack trace - could leak host information
316
+ };
317
+ }
318
+ return { error: message };
319
+ }
320
+ if (!isPlain && hasBrand(RegExpProtoSourceGetter, inspected)) {
321
+ return regExpToString(inspected);
322
+ }
323
+ if (!isPlain && hasBrand(MapProtoSizeGetter, inspected)) {
324
+ const sanitizedMap = ObjectCreate(null);
325
+ const entries = ReflectApply(MapProtoEntries, inspected, []);
326
+ for (const [key, val] of entries) {
327
+ if (typeof key !== "string") continue;
328
+ if (DANGEROUS_KEYS2.has(key)) continue;
329
+ context.propCount.count++;
330
+ sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
331
+ }
332
+ return sanitizedMap;
333
+ }
334
+ if (!isPlain && hasBrand(SetProtoSizeGetter, inspected)) {
335
+ const iter = ReflectApply(SetProtoValues, inspected, []);
336
+ const result = [];
337
+ for (const item of iter) {
338
+ context.propCount.count++;
339
+ result.push(sanitizeValue(item, options, depth + 1, context));
340
+ }
341
+ return result;
342
+ }
343
+ if (type === "object") {
344
+ const sanitized = ObjectCreate(null);
345
+ const keys = ObjectKeys(value);
346
+ context.propCount.count += keys.length;
347
+ if (context.propCount.count > maxProperties) {
348
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
349
+ }
350
+ for (const key of keys) {
351
+ if (DANGEROUS_KEYS2.has(key)) {
352
+ continue;
353
+ }
354
+ let propValue;
355
+ try {
356
+ propValue = ReflectGet2(value, key);
357
+ } catch {
358
+ continue;
359
+ }
360
+ sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
361
+ }
362
+ return sanitized;
363
+ }
364
+ return String(value);
365
+ }
366
+
367
+ // libs/core/src/tool-namespaces.ts
368
+ var TOOL_NAMESPACE_FACTORY_SOURCE = `
369
+ (function () {
370
+ 'use strict';
371
+ var parse = JSON.parse;
372
+ var freeze = Object.freeze;
373
+ var isArray = Array.isArray;
374
+
375
+ function isSafeKey(key) {
376
+ return typeof key === 'string' && key.length > 0 &&
377
+ !(key.charAt(0) === '_' && key.charAt(1) === '_') &&
378
+ key !== 'constructor' && key !== 'prototype';
379
+ }
380
+
381
+ function bind(callTool, toolName) {
382
+ return (args, options) => callTool(toolName, args === undefined ? {} : args, options);
383
+ }
384
+
385
+ return function install(callTool, namespacesJson) {
386
+ var spec = parse(namespacesJson);
387
+ var namespaces = { __proto__: null };
388
+ if (isArray(spec)) {
389
+ for (var i = 0; i < spec.length; i++) {
390
+ var ns = spec[i];
391
+ if (!ns || !isSafeKey(ns.name) || !isArray(ns.methods)) continue;
392
+ var target = { __proto__: null };
393
+ for (var j = 0; j < ns.methods.length; j++) {
394
+ var method = ns.methods[j];
395
+ if (!method || !isSafeKey(method.name) || typeof method.toolName !== 'string') continue;
396
+ target[method.name] = bind(callTool, method.toolName);
397
+ }
398
+ freeze(target);
399
+ namespaces[ns.name] = target;
400
+ }
401
+ }
402
+ freeze(namespaces);
403
+ return namespaces;
404
+ };
405
+ })()
406
+ `.trim();
407
+ function buildToolNamespaceBindings(install, callTool, namespaces) {
408
+ if (namespaces.length === 0) return [];
409
+ if (typeof install !== "function") {
410
+ throw new Error("Tool namespace factory is not available in the sandbox");
411
+ }
412
+ const built = install(
413
+ callTool,
414
+ JSON.stringify(namespaces)
415
+ );
416
+ return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
417
+ }
418
+
153
419
  // libs/core/src/adapters/worker-pool/worker-script.ts
154
420
  var STACK_TRACE_HARDENING_CODE = `
155
421
  (function() {
@@ -299,6 +565,7 @@ var CODE_GENERATION_VIOLATION_DETECTOR_CODE = `
299
565
  })();
300
566
  `.trim();
301
567
  var CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new import_vm.default.Script(CODE_GENERATION_VIOLATION_DETECTOR_CODE);
568
+ var TOOL_NAMESPACE_FACTORY_SCRIPT = new import_vm.default.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
302
569
  var port = import_worker_threads.parentPort;
303
570
  if (!port) {
304
571
  throw new Error("worker-script.ts must run inside a worker thread");
@@ -327,6 +594,9 @@ for (const name of DANGEROUS_GLOBALS) {
327
594
  }
328
595
  var currentExecution = null;
329
596
  var pendingToolCalls = /* @__PURE__ */ new Map();
597
+ function plainResult(fields) {
598
+ return Object.assign(/* @__PURE__ */ Object.create(null), fields);
599
+ }
330
600
  port.on("message", async (raw) => {
331
601
  try {
332
602
  const msg = safeDeserialize(raw);
@@ -374,6 +644,21 @@ async function handleExecute(msg) {
374
644
  });
375
645
  const isStrictOrSecure = msg.config.securityLevel === "STRICT" || msg.config.securityLevel === "SECURE";
376
646
  const policyViolation = {};
647
+ const toolNamespaces = msg.config.toolNamespaces ?? [];
648
+ if (toolNamespaces.length > 0) {
649
+ const install = TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(context);
650
+ const callTool = context["__safe_callTool"];
651
+ for (const binding of buildToolNamespaceBindings(install, callTool, toolNamespaces)) {
652
+ for (const name of [binding.name, `__safe_${binding.name}`]) {
653
+ Object.defineProperty(context, name, {
654
+ value: binding.value,
655
+ writable: false,
656
+ configurable: false,
657
+ enumerable: false
658
+ });
659
+ }
660
+ }
661
+ }
377
662
  const shouldHardenStacks = msg.config.sanitizeStackTraces ?? true;
378
663
  if (shouldHardenStacks) {
379
664
  try {
@@ -419,11 +704,18 @@ async function handleExecute(msg) {
419
704
  });
420
705
  return;
421
706
  }
707
+ const { value, specialValues } = encodeResult(
708
+ sanitizeValue(result, {
709
+ maxDepth: msg.config.maxSanitizeDepth,
710
+ maxProperties: msg.config.maxSanitizeProperties
711
+ })
712
+ );
422
713
  sendMessage({
423
714
  type: "result",
424
715
  requestId: msg.requestId,
425
716
  success: true,
426
- value: sanitizeObject(result),
717
+ value,
718
+ ...specialValues.length > 0 ? { specialValues } : {},
427
719
  stats: currentExecution.stats
428
720
  });
429
721
  } catch (error) {
@@ -462,11 +754,26 @@ function handleToolResponse(msg) {
462
754
  }
463
755
  pendingToolCalls.delete(msg.callId);
464
756
  if (msg.error) {
757
+ if (!pending.throwOnError && msg.toolError === true) {
758
+ pending.resolve(
759
+ plainResult({
760
+ success: false,
761
+ error: plainResult({
762
+ name: msg.error.name,
763
+ message: msg.error.message,
764
+ ...typeof msg.error.code === "string" ? { code: msg.error.code } : {},
765
+ toolName: pending.toolName
766
+ })
767
+ })
768
+ );
769
+ return;
770
+ }
465
771
  const error = new Error(msg.error.message);
466
772
  error.name = msg.error.name;
467
773
  pending.reject(error);
468
774
  } else {
469
- pending.resolve(sanitizeObject(msg.result));
775
+ const result = sanitizeObject(msg.result);
776
+ pending.resolve(pending.throwOnError ? result : plainResult({ success: true, data: result }));
470
777
  }
471
778
  }
472
779
  function handleMemoryReport() {
@@ -624,7 +931,14 @@ function createSandbox(requestId, config) {
624
931
  return sandbox;
625
932
  }
626
933
  function createProxiedCallTool(requestId, config) {
627
- return async function __safe_callTool(toolName, args) {
934
+ return async function __safe_callTool(toolName, args, options) {
935
+ let throwOnError = true;
936
+ if (options !== void 0 && options !== null) {
937
+ if (typeof options !== "object") {
938
+ throw new TypeError("callTool options must be an object");
939
+ }
940
+ throwOnError = options.throwOnError !== false;
941
+ }
628
942
  if (currentExecution?.aborted) {
629
943
  throw new Error("Execution aborted");
630
944
  }
@@ -644,7 +958,7 @@ function createProxiedCallTool(requestId, config) {
644
958
  }
645
959
  const callId = `${requestId}-${Date.now()}-${import_crypto.default.randomUUID()}`;
646
960
  return new Promise((resolve, reject) => {
647
- pendingToolCalls.set(callId, { resolve, reject });
961
+ pendingToolCalls.set(callId, { resolve, reject, throwOnError, toolName });
648
962
  sendMessage({
649
963
  type: "tool-call",
650
964
  requestId,
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Stack Trace Sanitization
3
+ *
4
+ * One sanitizer for every error the enclave hands back to its caller, whichever stage raised it
5
+ * (validation, transformation, compilation, execution, tool calls) and whichever adapter ran the
6
+ * script. With `sanitizeStackTraces` on, a returned stack keeps its message lines (with paths,
7
+ * locations and credential-like strings redacted) and every stack frame becomes `at [REDACTED]`,
8
+ * so no host path, file name, line or column number, or host function name survives.
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ /**
13
+ * Sensitive patterns redacted from the non-frame lines of a stack (the error header, and the
14
+ * source excerpt V8 prints for syntax errors).
15
+ *
16
+ * Categories covered:
17
+ * - File system paths (Unix, Windows, UNC), file URLs and file locations (`name.js:10:5`)
18
+ * - Cloud, container and CI paths
19
+ * - Secret/credential patterns
20
+ * - Internal hostnames and IPs
21
+ * - Package manager cache paths
22
+ */
23
+ export declare const SENSITIVE_STACK_PATTERNS: readonly RegExp[];
24
+ /**
25
+ * Sanitize a stack trace for the enclave's caller.
26
+ *
27
+ * With `sanitize` on, every frame line becomes `at [REDACTED]` and sensitive data in the other
28
+ * lines is redacted (see {@link SENSITIVE_STACK_PATTERNS}); the number of frames is preserved so
29
+ * the shape of the error stays recognizable. With `sanitize` off, the stack is returned unchanged.
30
+ *
31
+ * Only simple, non-nested patterns are applied, one bounded line at a time (the stack is cut at
32
+ * 16 KiB and each line at 1000 characters), so hostile input cannot make sanitization expensive.
33
+ *
34
+ * @param stack Original stack trace
35
+ * @param sanitize Whether to sanitize (defaults to true)
36
+ * @returns The sanitized stack trace (or the original if `sanitize` is false)
37
+ */
38
+ export declare function sanitizeStackTrace(stack: string | undefined, sanitize?: boolean): string | undefined;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Tool Namespace Bindings
3
+ *
4
+ * Builds the `toolNamespaces` objects (`mail.list(args)`) INSIDE a sandbox realm. The objects and
5
+ * their methods are created by code evaluated in that realm, so the script never receives a host
6
+ * object: each namespace is a frozen, null-prototype object whose methods are realm-local arrow
7
+ * functions that call the realm's own `callTool` (and therefore the enclave's tool-call gate).
8
+ *
9
+ * The configuration crosses into the realm as a JSON string and is parsed there. No source code is
10
+ * generated from it; names were validated by `normalizeToolNamespaces` on the host, and the
11
+ * factory skips prototype keys again as defense in depth.
12
+ *
13
+ * @packageDocumentation
14
+ */
15
+ import type { NormalizedToolNamespace } from '@enclave-vm/ast';
16
+ /**
17
+ * Source of an expression that, evaluated in a sandbox realm, captures that realm's `JSON.parse`
18
+ * and `Object.freeze` and returns `install(callTool, namespacesJson)`.
19
+ *
20
+ * `install` returns a frozen, null-prototype map from namespace name to namespace object. Each
21
+ * method is `(args, options) => callTool(toolName, args === undefined ? {} : args, options)`.
22
+ */
23
+ export declare const TOOL_NAMESPACE_FACTORY_SOURCE: string;
24
+ /** A namespace name paired with the realm-local object that implements it. */
25
+ export interface ToolNamespaceBinding {
26
+ readonly name: string;
27
+ readonly value: unknown;
28
+ }
29
+ /**
30
+ * Build the namespace objects with an `install` function obtained by evaluating
31
+ * {@link TOOL_NAMESPACE_FACTORY_SOURCE} in the sandbox realm.
32
+ *
33
+ * @param install The realm-local `install` function
34
+ * @param callTool The realm's gated `callTool`
35
+ * @param namespaces Validated namespaces
36
+ * @returns One binding per namespace, in configuration order
37
+ */
38
+ export declare function buildToolNamespaceBindings(install: unknown, callTool: unknown, namespaces: readonly NormalizedToolNamespace[]): ToolNamespaceBinding[];