# Content-Security-Policy Auditor (`phoenix2810/csp-auditor`) Actor

Deeply audit a public URL's Content-Security-Policy and Content-Security-Policy-Report-Only headers. Parses directives and sources, flags unsafe-inline, unsafe-eval, non-HTTPS sources, wildcards, missing default-src and frame-ancestors, nonces, hashes, and deprecated directives.

- **URL**: https://apify.com/phoenix2810/csp-auditor.md
- **Developed by:** [Sanskar Jaiswal](https://apify.com/phoenix2810) (community)
- **Categories:** Developer tools, SEO tools, Open source
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-usage

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## Content-Security-Policy Auditor

Fetches one public URL and deeply audits its `Content-Security-Policy` and `Content-Security-Policy-Report-Only` response headers. Parses every directive and source, flags `unsafe-inline`, `unsafe-eval`, non-HTTPS sources, wildcards, missing `default-src` and `frame-ancestors`, nonces and hashes, deprecated directives (`report-uri`, `plugin-types`, `prefetch-src`, `child-src`), and duplicate directives. Returns a readiness score, letter grade, issues, and recommendations. Built for security teams, devops engineers, frontend platform teams, site migration QA, and agency consultants.

### Use cases

- Verify a deployed CSP blocks inline scripts and eval after a release or cutover.
- Detect unsafe inline/eval or wildcard sources that weaken XSS protection before a launch.
- Catch missing `default-src` or `frame-ancestors` so per-directive coverage gaps and clickjacking are visible.
- Spot deprecated directives (`report-uri`, `plugin-types`, `prefetch-src`, `child-src`) and migrate to the Reporting API and `frame-src`/`worker-src`.
- Find duplicate directives that silently shadow each other (only the first is applied).
- Run scheduled checks on critical origins to catch CSP configuration drift on edge servers.
- Feed structured results into security QA dashboards or CI pipelines.

### Input

| Field | Type | Description |
| --- | --- | --- |
| `startUrl` | string | Public HTTP or HTTPS URL to audit. URLs with credentials and private network targets are rejected. |
| `timeoutSeconds` | integer | Request timeout from 3 to 30 seconds. Defaults to 10. |

### Output

The actor pushes one dataset item per run.

| Field | Type | Description |
| --- | --- | --- |
| `inputUrl` | string | Original URL from input. |
| `normalizedInputUrl` | string | Normalized input URL after defaulting the scheme. |
| `finalUrl` | string | Final page URL after redirects. |
| `https` | boolean | True when the final URL is HTTPS. |
| `ok` | boolean | True when the fetch succeeded. |
| `checkedAt` | string | ISO timestamp for the audit. |
| `httpStatus` | integer or null | HTTP status code from the response. |
| `hasCsp` | boolean | True when a `Content-Security-Policy` header is present. |
| `hasReportOnly` | boolean | True when a `Content-Security-Policy-Report-Only` header is present. |
| `rawCsp` | string or null | Raw `Content-Security-Policy` header value. |
| `rawReportOnly` | string or null | Raw `Content-Security-Policy-Report-Only` header value. |
| `reportingEndpoints` | string or null | `Reporting-Endpoints` header value, if present. |
| `reportTo` | string or null | `Report-To` header value, if present (deprecated). |
| `directives` | array | Parsed CSP directives, each with `name`, `sources`, audit flags, and per-directive issues. |
| `directiveCount` | integer | Number of parsed directives. |
| `sourceCount` | integer | Total number of source expressions across all directives. |
| `unsafeInline` | boolean | True when any directive contains `'unsafe-inline'`. |
| `unsafeEval` | boolean | True when any directive contains `'unsafe-eval'`. |
| `unsafeHashes` | boolean | True when any directive contains `'unsafe-hashes'`. |
| `hasWildcardSource` | boolean | True when a fetch directive uses a wildcard host or `*`. |
| `hasNonHttpsSource` | boolean | True when a fetch directive lists an `http://` URL or the `http:` scheme source. |
| `hasDefaultSrc` | boolean | True when `default-src` is present. |
| `hasFrameAncestors` | boolean | True when `frame-ancestors` is present. |
| `hasNonce` | boolean | True when a `'nonce-...'` source is present. |
| `hasHash` | boolean | True when a `'sha256-...'`, `'sha384-...'`, or `'sha512-...'` source is present. |
| `deprecatedDirectives` | array | List of deprecated directive names found (`report-uri`, `plugin-types`, `prefetch-src`, `child-src`). |
| `deprecatedDirectiveCount` | integer | Number of deprecated directives found. |
| `duplicateDirectives` | array | List of directive names that appear more than once. |
| `duplicateDirectiveCount` | integer | Number of duplicate directive names. |
| `score` | integer | CSP readiness score from 0 to 100. |
| `grade` | string | Letter grade from A+ to F. |
| `issues` | array | Human-readable issues with `directive` and `severity` where applicable. |
| `recommendations` | array | Suggested fixes. |
| `error` | string or null | Fetch-level error, if the request failed. |

### Example input

```json
{
  "startUrl": "https://example.com/",
  "timeoutSeconds": 10
}
```

### Example output

```json
{
  "inputUrl": "https://example.com/",
  "normalizedInputUrl": "https://example.com/",
  "finalUrl": "https://example.com/",
  "https": true,
  "ok": true,
  "checkedAt": "2025-01-01T00:00:00.000Z",
  "httpStatus": 200,
  "hasCsp": true,
  "hasReportOnly": false,
  "rawCsp": "default-src 'none'; script-src 'self' 'nonce-abc123='; frame-ancestors 'none'",
  "rawReportOnly": null,
  "reportingEndpoints": null,
  "reportTo": null,
  "directives": [
    {
      "name": "default-src",
      "sources": ["'none'"],
      "isFetchDirective": true,
      "isDeprecated": false,
      "keywords": ["'none'"],
      "unsafeInline": false,
      "unsafeEval": false,
      "unsafeHashes": false,
      "hasNonce": false,
      "hasHash": false,
      "hasWildcard": false,
      "hasNonHttps": false,
      "nonHttpsSources": [],
      "wildcardSources": [],
      "issues": []
    },
    {
      "name": "script-src",
      "sources": ["'self'", "'nonce-abc123='"],
      "isFetchDirective": true,
      "isDeprecated": false,
      "keywords": ["'self'"],
      "unsafeInline": false,
      "unsafeEval": false,
      "unsafeHashes": false,
      "hasNonce": true,
      "hasHash": false,
      "hasWildcard": false,
      "hasNonHttps": false,
      "nonHttpsSources": [],
      "wildcardSources": [],
      "issues": []
    },
    {
      "name": "frame-ancestors",
      "sources": ["'none'"],
      "isFetchDirective": true,
      "isDeprecated": false,
      "keywords": ["'none'"],
      "unsafeInline": false,
      "unsafeEval": false,
      "unsafeHashes": false,
      "hasNonce": false,
      "hasHash": false,
      "hasWildcard": false,
      "hasNonHttps": false,
      "nonHttpsSources": [],
      "wildcardSources": [],
      "issues": []
    }
  ],
  "directiveCount": 3,
  "sourceCount": 5,
  "unsafeInline": false,
  "unsafeEval": false,
  "unsafeHashes": false,
  "hasWildcardSource": false,
  "hasNonHttpsSource": false,
  "hasDefaultSrc": true,
  "hasFrameAncestors": true,
  "hasNonce": true,
  "hasHash": false,
  "deprecatedDirectives": [],
  "deprecatedDirectiveCount": 0,
  "duplicateDirectives": [],
  "duplicateDirectiveCount": 0,
  "score": 100,
  "grade": "A+",
  "issues": [],
  "recommendations": [
    "CSP posture looks strong; consider load-testing with report-only changes and monitor CSP reports."
  ],
  "error": null
}
```

### Security

- Only public HTTP and HTTPS URLs are fetched.
- URLs with usernames or passwords are rejected.
- Private IPv4, private IPv6, localhost, link-local, and private DNS resolutions are blocked before fetching.
- Redirect destinations are revalidated before they are followed.
- The actor does not require logins, cookies, browser sessions, or credentials.
- The actor fetches headers only; it does not fetch any URLs referenced inside the CSP.

### Pricing

| Event | Suggested price |
| --- | ---: |
| Actor start | `$0.005` |
| URL audited | `$0.01` |

Suggested launch price: about `$0.015` per audited URL. Teams can schedule the actor for recurring checks on important origins after deploys and CDN cutovers.

### FAQ

#### Does this actor crawl multiple URLs or a whole site?

No. It fetches one URL per run. This keeps runs cheap and predictable for CI and scheduled monitoring.

#### How does the score work?

The score starts at 100 and is reduced for: `unsafe-inline` (-25), `unsafe-eval` (-20), `unsafe-hashes` (-10), wildcard sources (-15), non-HTTPS sources (-10), missing `frame-ancestors` (-5), deprecated directives (-3 each, capped at -10), and duplicate directives (-4 each, capped at -8). A modern nonce/hash posture without `unsafe-inline` adds +5 (capped at 100). Policies that enforce nothing (`Content-Security-Policy` absent) receive an `F`.

#### Why does this actor check `Content-Security-Policy-Report-Only` separately?

`Content-Security-Policy-Report-Only` is intentionally advisory; browsers report violations without blocking. The actor parses it and surfaces structural issues (missing `default-src`, unsafe keywords, wildcards) but the readiness score is computed from the enforced `Content-Security-Policy` when present.

#### Which directives are considered deprecated?

`report-uri` (replaced by the Reporting API and `Reporting-Endpoints`), `plugin-types` (removed in CSP3, replaced by `X-Content-Type-Options`), `prefetch-src` (removed in CSP3), and `child-src` (deprecated in favor of `frame-src` and `worker-src`).

#### How are duplicate directives handled?

When a directive name appears more than once in the same policy, the actor reports each duplicate name. Browsers apply only the first declaration and silently ignore the rest, so duplicates usually indicate a configuration mistake.

#### What is the difference between this actor and the HTTP Security Headers Auditor?

The HTTP Security Headers Auditor checks ten security response headers at a high level and treats CSP as one of them. This Content-Security-Policy Auditor is specialized: it parses every CSP directive and source, evaluates fetch-directive coverage, classifies unsafe keywords, non-HTTPS sources, wildcards, nonces, hashes, deprecated directives, and duplicates, and returns a recommended hardening path for CSP specifically.

# Actor input Schema

## `startUrl` (type: `string`):

Public HTTP or HTTPS URL to audit.

## `timeoutSeconds` (type: `integer`):

Request timeout from 3 to 30 seconds.

## Actor input object example

```json
{
  "startUrl": "https://example.com/",
  "timeoutSeconds": 10
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "startUrl": "https://example.com/"
};

// Run the Actor and wait for it to finish
const run = await client.actor("phoenix2810/csp-auditor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "startUrl": "https://example.com/" }

# Run the Actor and wait for it to finish
run = client.actor("phoenix2810/csp-auditor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "startUrl": "https://example.com/"
}' |
apify call phoenix2810/csp-auditor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,phoenix2810/csp-auditor"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/sJqjBkBEg2bSZzEhh/builds/Snss32oJP9hJeeGB8/openapi.json
