> ## 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.

# Blackbox Pentest

> Run a complete deterministic penetration testing workflow

## Overview

The Blackbox Pentest API orchestrates a full penetration testing workflow that combines attack surface discovery with targeted exploitation. It automatically spawns multiple specialized agents to test discovered targets in parallel.

**Key Features:**

* Two-phase workflow: reconnaissance then exploitation
* Supports both blackbox and whitebox testing modes
* Automatic target prioritization and agent spawning
* Parallel execution with configurable concurrency
* Comprehensive finding deduplication
* Automatic report generation

***

## runPentestAgent

Run the deterministic pentest workflow (blackbox or whitebox based on input).

**Workflow Phases:**

1. **Phase 1**: Runs attack surface discovery (whitebox workflow or blackbox agent)
2. **Phase 2**: Spawns targeted pentest agents for each discovered target
3. **Phase 3**: Aggregates results and generates report

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

const result = await runPentestAgent({
  target: 'https://example.com',
  model: 'claude-sonnet-4-20250514',
  session: sessionInfo,
  callbacks: {
    onTextDelta: (d) => process.stdout.write(d.text),
    subagentCallbacks: {
      onSubagentSpawn: ({ subagentId, status }) => {
        console.log(`${subagentId}: ${status}`);
      },
      onSubagentComplete: ({ subagentId, status }) => {
        console.log(`${subagentId}: ${status}`);
      },
    },
  },
});

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

### Parameters

<ParamField path="input" type="PentestWorkflowInput" required>
  Configuration for the pentest workflow

  <Expandable title="PentestWorkflowInput properties">
    <ParamField path="target" type="string" required>
      Live target URL — always required
    </ParamField>

    <ParamField path="cwd" type="string">
      Local codebase path. When provided, enables whitebox attack surface analysis.
    </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="authConfig" type="AIAuthConfig">
      Optional per-provider API key overrides
    </ParamField>

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

    <ParamField path="callbacks" type="ConsumeCallbacks">
      Stream event callbacks for monitoring workflow 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 an 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>

        <ParamField path="subagentCallbacks" type="SubagentConsumeCallbacks">
          Callbacks for monitoring spawned pentest agents

          <Expandable title="SubagentConsumeCallbacks properties">
            <ParamField path="onSubagentSpawn" type="(event) => void">
              Called when a new pentest agent is spawned
            </ParamField>

            <ParamField path="onSubagentComplete" type="(event) => void">
              Called when a pentest agent completes
            </ParamField>

            <ParamField path="onTextDelta" type="(delta) => void">
              Text deltas from subagents (includes `subagentId`)
            </ParamField>

            <ParamField path="onToolCall" type="(delta) => void">
              Tool calls from subagents (includes `subagentId`)
            </ParamField>

            <ParamField path="onToolResult" type="(delta) => void">
              Tool results from subagents (includes `subagentId`)
            </ParamField>
          </Expandable>
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

### Response

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

  <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
    </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 and resources (optional)
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="findingsPath" type="string">
  Absolute path to the session's findings directory
</ResponseField>

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

<ResponseField name="reportPath" type="string | null">
  Path to the generated pentest report (null if not generated)
</ResponseField>

***

## Usage Examples

<CodeGroup>
  ```typescript Basic Blackbox Pentest theme={null}
  import { runPentestAgent } from '@pensar/apex/api/blackboxPentest';
  import { createSession } from '@pensar/apex/session';

  // Create session
  const session = await createSession({
    name: 'Full Pentest',
    targets: ['https://example.com'],
  });

  // Run full pentest workflow
  const result = await runPentestAgent({
    target: 'https://example.com',
    model: 'claude-sonnet-4-20250514',
    session,
  });

  console.log(`Findings: ${result.findingsPath}`);
  console.log(`POCs: ${result.pocsPath}`);
  if (result.reportPath) {
    console.log(`Report: ${result.reportPath}`);
  }
  ```

  ```typescript Whitebox Pentest theme={null}
  import { runPentestAgent } from '@pensar/apex/api/blackboxPentest';
  import { createSession } from '@pensar/apex/session';

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

  // Run whitebox pentest (includes source code analysis)
  const result = await runPentestAgent({
    target: 'https://staging.example.com',
    cwd: '/path/to/project',  // Enables whitebox mode
    model: 'claude-sonnet-4-20250514',
    session,
  });

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

  // Process findings
  for (const finding of result.findings) {
    console.log(`[${finding.severity}] ${finding.title}`);
    console.log(`  Endpoint: ${finding.endpoint}`);
    console.log(`  PoC: ${finding.pocPath}`);
  }
  ```

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

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

  const agentsSpawned = new Set();

  const result = await runPentestAgent({
    target: 'https://api.example.com',
    model: 'claude-sonnet-4-20250514',
    session,
    callbacks: {
      onTextDelta: (d) => process.stdout.write(d.text),
      onToolCall: (d) => console.log(`\n→ ${d.toolName}`),
      onToolResult: (d) => console.log(`✓ ${d.toolName}`),
      
      subagentCallbacks: {
        onSubagentSpawn: ({ subagentId, input, status }) => {
          agentsSpawned.add(subagentId);
          console.log(`\n[${subagentId}] Spawned`);
          console.log(`  Target: ${input.target}`);
          console.log(`  Objectives: ${input.objectives.join(', ')}`);
        },
        
        onSubagentComplete: ({ subagentId, status }) => {
          console.log(`\n[${subagentId}] ${status}`);
        },
        
        onTextDelta: ({ subagentId, text }) => {
          process.stdout.write(`[${subagentId}] ${text}`);
        },
      },
    },
  });

  console.log(`\n\nSummary:`);
  console.log(`Agents spawned: ${agentsSpawned.size}`);
  console.log(`Vulnerabilities found: ${result.findings.length}`);
  ```

  ```typescript With Cancellation theme={null}
  import { runPentestAgent } from '@pensar/apex/api/blackboxPentest';
  import { createSession } from '@pensar/apex/session';

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

  // Create abort controller for cancellation
  const abortController = new AbortController();

  // Cancel after 30 minutes
  setTimeout(() => {
    console.log('\nCancelling pentest...');
    abortController.abort();
  }, 30 * 60 * 1000);

  try {
    const result = await runPentestAgent({
      target: 'https://example.com',
      model: 'claude-sonnet-4-20250514',
      session,
      abortSignal: abortController.signal,
    });
    
    console.log(`Completed: ${result.findings.length} findings`);
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Pentest was cancelled');
    } else {
      throw error;
    }
  }
  ```
</CodeGroup>

***

## Workflow Details

### Phase 1: Attack Surface Discovery

The workflow begins by discovering the attack surface:

* **Blackbox mode** (default): Runs external reconnaissance using web scraping, DNS enumeration, port scanning, and browser automation
* **Whitebox mode** (when `cwd` provided): Analyzes source code to extract API endpoints, routes, and pages

Both modes produce a list of prioritized targets with specific testing objectives.

### Phase 2: Parallel Exploitation

The workflow spawns multiple `TargetedPentestAgent` instances (default: 10 concurrent) to test each target:

* Each agent receives specific targets and objectives from Phase 1
* Agents run in parallel with bounded concurrency
* Findings are automatically deduplicated via shared registry
* Progress is tracked via subagent callbacks

### Phase 3: Result Aggregation

After all agents complete:

* All findings are collected from the session's findings directory
* A comprehensive pentest report is generated (if applicable)
* Results are returned with paths to findings, POCs, and reports

***

## Related APIs

<CardGroup cols={2}>
  <Card title="Attack Surface" icon="radar" href="/api/attack-surface">
    Run attack surface discovery separately
  </Card>

  <Card title="Targeted Pentest" icon="bullseye" href="/api/targeted-pentest">
    Test specific targets without discovery
  </Card>

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

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