sandboxEnforcementHook static method

HookRegistration sandboxEnforcementHook({
  1. required List<String> allowedPaths,
  2. required bool isInSandbox(
    1. String path
    ),
})

Hook that enforces sandbox restrictions on file and shell operations.

Prevents access to paths outside the allowed sandbox. Runs at HookPriority.critical.

Implementation

static HookRegistration sandboxEnforcementHook({
  required List<String> allowedPaths,
  required bool Function(String path) isInSandbox,
}) {
  return HookRegistration(
    id: 'builtin:sandbox-enforcement',
    type: HookType.preToolExecution,
    priority: HookPriority.critical,
    name: 'Sandbox Enforcement',
    description: 'Ensures operations stay within the sandbox.',
    source: 'builtin',
    tags: {'security', 'sandbox'},
    handler: (context) {
      if (context is! ToolHookContext) return const HookContinue();

      // Check file paths in tool input
      final path =
          context.toolInput['file_path'] as String? ??
          context.toolInput['path'] as String?;
      if (path != null && !isInSandbox(path)) {
        return HookAbort(
          'Path "$path" is outside the sandbox. '
          'Allowed paths: ${allowedPaths.join(", ")}',
        );
      }
      return const HookContinue();
    },
  );
}