> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/pensarai/apex/llms.txt
> Use this file to discover all available pages before exploring further.

# Targeted Pentest

> Execute penetration tests against specific targets with defined objectives

## Overview

The Targeted Pentest API provides focused penetration testing capabilities for specific targets and objectives. Unlike the full workflow, this API allows you to test individual endpoints or features with precise testing goals.

**Key Features:**

* Focused testing on specific targets
* Custom testing objectives per target
* Automatic PoC script generation
* Finding deduplication across runs
* Sandbox support for isolated execution
* Browser automation for complex testing scenarios

***

## runTargetedPentestAgent

Run a targeted penetration test against a specific target with defined objectives.

**Testing Methodology:**

1. **PLAN**: State objectives and outline testing approach
2. **VERIFY**: Confirm target is reachable and understand baseline behavior
3. **PREPARE**: Research payloads and attack techniques
4. **TEST**: Execute targeted attacks methodically
5. **EXPLOIT**: Create proof-of-concept scripts
6. **DOCUMENT**: Document confirmed vulnerabilities
7. **FINISH**: Submit final summary

```typescript theme={null}
import { runTargetedPentestAgent } from '@pensar/apex/api/targetedPentest';

const result = await runTargetedPentestAgent({
  target: 'https://api.example.com/users',
  objectives: [
    'Test for SQL injection vulnerabilities',
    'Check for authentication bypass',
    'Test for broken access control',
  ],
  model: 'claude-sonnet-4-20250514',
  session: sessionInfo,
});

console.log(`Found ${result.findings.length} vulnerabilities`);
```

### Parameters

<ParamField path="input" type="PentestAgentInput" required>
  Configuration for the targeted pentest agent

  <Expandable title="PentestAgentInput properties">
    <ParamField path="target" type="string" required>
      The URL or host to test (e.g., `"https://api.example.com/users"`)
    </ParamField>

    <ParamField path="objectives" type="string[]" required>
      One or more testing objectives. Each should be specific and actionable.

      Examples:

      * `"Test for SQL injection on /api/users"`
      * `"Check authentication bypass via JWT manipulation"`
      * `"Test IDOR on user profile endpoints"`
      * `"Test for XSS in search functionality"`
    </ParamField>

    <ParamField path="model" type="AIModel" required>
      AI model identifier (e.g., `"claude-sonnet-4-20250514"`)
    </ParamField>

    <ParamField path="session" type="SessionInfo" required>
      Session object providing paths for findings, POCs, logs, etc.
    </ParamField>

    <ParamField path="sandbox" type="UnifiedSandbox">
      When set, tools execute inside this sandbox instead of locally. Useful for isolated testing environments.
    </ParamField>

    <ParamField path="findingsRegistry" type="FindingsRegistry">
      Shared findings registry for cross-agent deduplication. When provided, the agent checks for duplicate vulnerabilities before documenting.
    </ParamField>

    <ParamField path="authConfig" type="AIAuthConfig">
      Optional per-provider API key overrides
    </ParamField>

    <ParamField path="abortSignal" type="AbortSignal">
      AbortSignal to cancel the agent mid-run
    </ParamField>

    <ParamField path="onStepFinish" type="StreamTextOnStepFinishCallback">
      Callback fired after each agent step completes
    </ParamField>

    <ParamField path="callbacks" type="ConsumeCallbacks">
      Stream event callbacks for monitoring agent progress

      <Expandable title="ConsumeCallbacks properties">
        <ParamField path="onTextDelta" type="(delta) => void">
          Called for each text chunk streamed from the AI
        </ParamField>

        <ParamField path="onToolCall" type="(delta) => void">
          Called when the agent invokes a tool
        </ParamField>

        <ParamField path="onToolResult" type="(delta) => void">
          Called when a tool execution completes
        </ParamField>

        <ParamField path="onError" type="(error) => void">
          Called when an error occurs
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

### Response

<ResponseField name="findings" type="Finding[]">
  All vulnerability findings discovered during the test

  <Expandable title="Finding properties">
    <ResponseField name="title" type="string">
      Vulnerability title
    </ResponseField>

    <ResponseField name="severity" type="'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW'">
      Severity level
    </ResponseField>

    <ResponseField name="description" type="string">
      Detailed description of the vulnerability
    </ResponseField>

    <ResponseField name="impact" type="string">
      Impact assessment and potential consequences
    </ResponseField>

    <ResponseField name="evidence" type="string">
      Evidence demonstrating the vulnerability (logs, screenshots, responses)
    </ResponseField>

    <ResponseField name="endpoint" type="string">
      Affected endpoint or URL
    </ResponseField>

    <ResponseField name="pocPath" type="string">
      Path to the proof-of-concept exploit script
    </ResponseField>

    <ResponseField name="remediation" type="string">
      Recommended remediation steps
    </ResponseField>

    <ResponseField name="references" type="string">
      External references (CVEs, CWEs, documentation) - optional
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="findingsPath" type="string">
  Absolute path to the session's findings directory where JSON reports are stored
</ResponseField>

<ResponseField name="pocsPath" type="string">
  Absolute path to the session's POC scripts directory
</ResponseField>

***

## Usage Examples

<CodeGroup>
  ```typescript Basic Usage theme={null}
  import { runTargetedPentestAgent } from '@pensar/apex/api/targetedPentest';
  import { createSession } from '@pensar/apex/session';

  const session = await createSession({
    name: 'API Security Test',
    targets: ['https://api.example.com'],
  });

  const result = await runTargetedPentestAgent({
    target: 'https://api.example.com/users',
    objectives: [
      'Test for SQL injection in search parameter',
      'Check for broken access control on user updates',
    ],
    model: 'claude-sonnet-4-20250514',
    session,
  });

  console.log(`Found ${result.findings.length} vulnerabilities`);
  result.findings.forEach((finding) => {
    console.log(`[${finding.severity}] ${finding.title}`);
    console.log(`  PoC: ${finding.pocPath}`);
  });
  ```

  ```typescript With Authentication theme={null}
  import { runTargetedPentestAgent } from '@pensar/apex/api/targetedPentest';
  import { createSession } from '@pensar/apex/session';

  // Create session with auth credentials
  const session = await createSession({
    name: 'Authenticated Test',
    targets: ['https://app.example.com'],
    config: {
      authCredentials: {
        username: 'testuser',
        password: 'testpass',
        loginUrl: 'https://app.example.com/login',
      },
    },
  });

  // Agent automatically uses authenticated session
  const result = await runTargetedPentestAgent({
    target: 'https://app.example.com/api/admin/users',
    objectives: [
      'Test privilege escalation from regular user to admin',
      'Test IDOR on admin user management',
    ],
    model: 'claude-sonnet-4-20250514',
    session,
  });
  ```

  ```typescript With Findings Registry theme={null}
  import { runTargetedPentestAgent } from '@pensar/apex/api/targetedPentest';
  import { FindingsRegistry } from '@pensar/apex/findings';
  import { createSession } from '@pensar/apex/session';

  const session = await createSession({
    name: 'Multi-Target Test',
    targets: ['https://api.example.com'],
  });

  // Create shared registry for deduplication
  const registry = FindingsRegistry.fromDirectory(
    session.findingsPath,
    { model: 'claude-sonnet-4-20250514' },
  );

  // Test multiple targets with shared registry
  const targets = [
    { url: '/api/users', objectives: ['Test SQL injection'] },
    { url: '/api/posts', objectives: ['Test SQL injection'] },
    { url: '/api/comments', objectives: ['Test SQL injection'] },
  ];

  for (const target of targets) {
    const result = await runTargetedPentestAgent({
      target: `https://api.example.com${target.url}`,
      objectives: target.objectives,
      model: 'claude-sonnet-4-20250514',
      session,
      findingsRegistry: registry,  // Deduplicates across runs
    });
    
    console.log(`${target.url}: ${result.findings.length} new findings`);
  }
  ```

  ```typescript With Progress Monitoring theme={null}
  import { runTargetedPentestAgent } from '@pensar/apex/api/targetedPentest';
  import { createSession } from '@pensar/apex/session';

  const session = await createSession({
    name: 'Monitored Test',
    targets: ['https://api.example.com'],
  });

  const result = await runTargetedPentestAgent({
    target: 'https://api.example.com/checkout',
    objectives: [
      'Test payment manipulation',
      'Test order replay attacks',
    ],
    model: 'claude-sonnet-4-20250514',
    session,
    callbacks: {
      onTextDelta: (d) => process.stdout.write(d.text),
      
      onToolCall: (d) => {
        console.log(`\n→ calling ${d.toolName}`);
        if (d.args) {
          console.log(JSON.stringify(d.args, null, 2));
        }
      },
      
      onToolResult: (d) => {
        console.log(`✓ ${d.toolName} completed`);
      },
      
      onError: (e) => {
        console.error('Agent error:', e);
      },
    },
  });
  ```

  ```typescript With Sandbox Isolation theme={null}
  import { runTargetedPentestAgent } from '@pensar/apex/api/targetedPentest';
  import { createSandbox } from '@pensar/apex/sandbox';
  import { createSession } from '@pensar/apex/session';

  const session = await createSession({
    name: 'Sandboxed Test',
    targets: ['https://staging.example.com'],
  });

  // Create isolated sandbox
  const sandbox = await createSandbox({
    type: 'docker',
    image: 'pentest-tools:latest',
  });

  try {
    // All tool executions run inside sandbox
    const result = await runTargetedPentestAgent({
      target: 'https://staging.example.com/api/upload',
      objectives: [
        'Test file upload for code execution',
        'Test path traversal in file handling',
      ],
      model: 'claude-sonnet-4-20250514',
      session,
      sandbox,  // Tools execute in isolated environment
    });
    
    console.log(`Found ${result.findings.length} vulnerabilities`);
  } finally {
    await sandbox.destroy();
  }
  ```
</CodeGroup>

***

## Testing Guidelines

### Writing Effective Objectives

Objectives should be specific, actionable, and focused:

**Good objectives:**

* `"Test SQL injection in username parameter on login endpoint"`
* `"Check for authentication bypass via JWT token manipulation"`
* `"Test for IDOR vulnerabilities on user profile update (PUT /api/users/:id)"`
* `"Test XSS in post content and comment fields"`

**Avoid vague objectives:**

* `"Test the API"` (too broad)
* `"Find vulnerabilities"` (not actionable)
* `"Security test"` (no specific target)

### Available Testing Capabilities

The agent has access to these testing tools:

* **execute\_command**: Run shell commands (curl, custom scripts, exploit tools)
* **http\_request**: Make HTTP requests with custom headers/body
* **browser\_navigate**: Load pages in a headless browser
* **browser\_click**: Interact with buttons and links
* **browser\_fill**: Fill form fields
* **browser\_screenshot**: Capture visual evidence
* **document\_vulnerability**: Document confirmed findings
* **create\_poc**: Generate proof-of-concept exploit scripts

### Authentication Handling

If the session has authentication data (from prior auth or manual setup):

* The agent automatically includes cookies and headers in all requests
* Authentication is preserved across HTTP requests and browser actions
* Session expiration is detected and reported

***

## Related APIs

<CardGroup cols={2}>
  <Card title="Blackbox Pentest" icon="shield-halved" href="/api/blackbox-pentest">
    Full workflow with discovery + exploitation
  </Card>

  <Card title="Attack Surface" icon="radar" href="/api/attack-surface">
    Discover targets before testing
  </Card>

  <Card title="Authentication" icon="key" href="/api/authentication">
    Authenticate before testing
  </Card>

  <Card title="Patching" icon="bandage" href="/api/patching">
    Generate patches for findings
  </Card>
</CardGroup>
