An open API service indexing awesome lists of open source software.

https://github.com/tkachenko0/csp-playground

Interactive playground to learn CSP by seeing and preventing XSS attacks
https://github.com/tkachenko0/csp-playground

Last synced: about 1 month ago
JSON representation

Interactive playground to learn CSP by seeing and preventing XSS attacks

Awesome Lists containing this project

README

          

# Content Security Policy (CSP) Playground

Interactive playground to learn CSP by seeing an XSS attack succeed without it and fail with it.

## What is CSP?

Content Security Policy is an HTTP response header that tells the browser which sources of content are allowed to load and execute.

```
Content-Security-Policy: default-src 'self'; script-src 'self'
```

This tells the browser: "Only load scripts and other resources from the same origin."

## Start

```bash
docker compose up -d --build
```

Open http://localhost:8888 - you'll see two pages:

- **Without CSP**: injected inline script executes
The browser has no way to know which scripts are legitimate and which are injected. It executes everything.
- **With CSP**: browser blocks the inline script
The server sends `Content-Security-Policy: script-src 'self'` which tells the browser "only execute scripts loaded from my origin, block everything inline."

## CSP Violation Reports

The server includes `report-uri /csp-report` in the CSP header. When the browser blocks something, it sends a JSON report to that endpoint.

```bash
docker compose logs -f
```

## Nginx

In production, CSP is typically set at the reverse proxy level since it's just an HTTP response header. This demo uses Express because it needs to serve the same page both with and without the header to show the difference.

### Nginx Example

```nginx
server {
listen 80;
server_name example.com;

add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; frame-ancestors 'none'; form-action 'self';" always;

location / {
root /usr/share/nginx/html;
}

location /api/ {
proxy_pass http://backend:4000/;
}
}
```

## References

- [MDN: Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)
- [MDN: Content-Security-Policy report-to](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-to)