SE

sentry-security-basics

Secure Sentry projects by managing PII scrubbing, data protection, and access settings.

Install

mkdir -p .claude/skills/sentry-security-basics && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/8965" && unzip -o skill.zip -d .claude/skills/sentry-security-basics && rm skill.zip

Installs to .claude/skills/sentry-security-basics

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Configure Sentry security settings and data protection.
55 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Configure client-side PII scrubbing with beforeSend
  • Implement IP anonymization and cookie blocking
  • Manage DSN and auth token security
  • Filter sensitive data from request headers and bodies
  • Apply GDPR-compliant data deletion workflows

How it works

It utilizes the beforeSend hook to intercept and sanitize event payloads on the client side before they are transmitted to Sentry servers.

Inputs & outputs

You give it
Raw event data containing potential PII
You get back
Scrubbed event data sent to Sentry

When to use sentry-security-basics

  • Implement PII scrubbing rules
  • Configure GDPR data deletion workflows
  • Hardening Sentry projects for compliance
  • Set up Allowed Domains for DSN security

About this skill

Sentry Security Basics

Overview

Configure Sentry's security posture: PII scrubbing with beforeSend, built-in data scrubbing, IP anonymization, browser SDK URL filtering, DSN vs auth token handling, CSP reporting, and GDPR data deletion. Covers both client-side (SDK) and server-side (dashboard) controls.

Prerequisites

  • Sentry project created with Owner or Admin role
  • @sentry/node >= 8.x or @sentry/browser >= 8.x installed (or sentry-sdk >= 2.x for Python)
  • Compliance requirements identified (GDPR, SOC 2, HIPAA, CCPA)
  • List of sensitive data patterns for your domain (PII fields, API keys, tokens)

Instructions

Step 1 — Understand DSN vs Auth Token Security

The DSN (Data Source Name) is a client-facing identifier — it tells the SDK where to send events. It is NOT a secret.

https://<public-key>@o<org-id>.ingest.us.sentry.io/<project-id>
  • The DSN cannot read data, delete events, or modify settings
  • It is safe to ship in client-side JavaScript bundles
  • Restrict abuse via Allowed Domains (Project Settings > Client Keys > Configure)

Auth tokens ARE secrets — they grant API access to read/write/delete data:

# NEVER commit auth tokens — store in CI secrets or vault
# GitHub Actions: Settings > Secrets > SENTRY_AUTH_TOKEN
# GitLab CI: Settings > CI/CD > Variables (protected + masked)

# Generate tokens with MINIMAL scopes:
#   CI releases:   project:releases, org:read
#   Issue triage:  project:read, event:read
#   NEVER:         org:admin, member:admin in CI

# Rotate tokens quarterly — revoke unused tokens immediately
# Create separate tokens per pipeline (staging vs production)

Step 2 — Disable Default PII Collection

sendDefaultPii defaults to false — but always set it explicitly so intent is clear:

import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  sendDefaultPii: false, // explicit: no IPs, no cookies, no user-agent
});

When sendDefaultPii: false (default):

  • No IP addresses attached to events
  • No cookies sent in request data
  • No user-agent strings in request headers
  • No request body data captured
  • User context must be set manually via Sentry.setUser()
# Python equivalent
import sentry_sdk

sentry_sdk.init(
    dsn=os.environ["SENTRY_DSN"],
    send_default_pii=False,  # default, but be explicit
)

Step 3 — Client-Side PII Scrubbing with beforeSend

beforeSend runs before every event leaves the client. Use it to strip PII that leaks into error messages, request data, or breadcrumbs:

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  sendDefaultPii: false,

  beforeSend(event, hint) {
    // --- Scrub sensitive headers ---
    if (event.request?.headers) {
      delete event.request.headers['Authorization'];
      delete event.request.headers['Cookie'];
      delete event.request.headers['X-Api-Key'];
      delete event.request.headers['X-Auth-Token'];
    }

    // --- Scrub request body fields ---
    if (event.request?.data) {
      try {
        const data = typeof event.request.data === 'string'
          ? JSON.parse(event.request.data)
          : { ...event.request.data };

        const sensitiveKeys = [
          'password', 'passwd', 'secret', 'token',
          'ssn', 'credit_card', 'card_number', 'cvv',
          'api_key', 'apiKey', 'access_token', 'refresh_token',
        ];
        for (const key of Object.keys(data)) {
          if (sensitiveKeys.some(s => key.toLowerCase().includes(s))) {
            data[key] = '[REDACTED]';
          }
        }
        event.request.data = JSON.stringify(data);
      } catch {
        // non-JSON body — leave as-is
      }
    }

    // --- Scrub PII from exception messages ---
    if (event.exception?.values) {
      for (const exc of event.exception.values) {
        if (exc.value) {
          // Email addresses
          exc.value = exc.value.replace(
            /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
            '[EMAIL_REDACTED]'
          );
          // IPv4 addresses
          exc.value = exc.value.replace(
            /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
            '[IP_REDACTED]'
          );
          // Credit card numbers (with optional separators)
          exc.value = exc.value.replace(
            /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
            '[CC_REDACTED]'
          );
          // Bearer tokens in messages
          exc.value = exc.value.replace(
            /Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,
            'Bearer [TOKEN_REDACTED]'
          );
        }
      }
    }

    // --- Scrub user context ---
    if (event.user) {
      delete event.user.email;
      delete event.user.ip_address;
      // Keep event.user.id for issue grouping (non-PII identifier)
    }

    return event;
  },
});

Python equivalent using before_send:

import re

def before_send(event, hint):
    # Scrub emails from exception messages
    if 'exception' in event:
        for exc in event['exception'].get('values', []):
            if exc.get('value'):
                exc['value'] = re.sub(
                    r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
                    '[EMAIL_REDACTED]',
                    exc['value']
                )
                exc['value'] = re.sub(
                    r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b',
                    '[IP_REDACTED]',
                    exc['value']
                )

    # Strip user PII
    if 'user' in event:
        event['user'].pop('email', None)
        event['user'].pop('ip_address', None)

    # Scrub request headers
    request = event.get('request', {})
    headers = request.get('headers', {})
    for key in ['Authorization', 'Cookie', 'X-Api-Key']:
        headers.pop(key, None)

    return event

sentry_sdk.init(
    dsn=os.environ["SENTRY_DSN"],
    send_default_pii=False,
    before_send=before_send,
)

Step 4 — Server-Side Data Scrubbing Rules

Configure in Project Settings > Security & Privacy:

SettingWhat it does
Data ScrubberAuto-scrubs fields matching common PII patterns (enabled by default)
Sensitive FieldsCustom field names to always scrub: password, ssn, credit_card_number, api_key, secret, token, authorization
Safe FieldsFields excluded from scrubbing (e.g., transaction_id, correlation_id)
Scrub IP AddressesRemoves or zeroes IP addresses on all events
Scrub Credit CardsDetects and removes card number patterns

Organization-wide defaults: Organization Settings > Security & Privacy applies to all projects unless overridden at project level.

Advanced scrubbing rules (regex-based) can target specific event paths:

# Example server-side rules (configure in UI):
# Pattern: [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
# Target:  $message, $error.value, $extra.**
# Action:  Replace with [Filtered]

# Pattern: \b\d{3}-\d{2}-\d{4}\b
# Target:  $extra.**, $contexts.**
# Action:  Replace with [Filtered] (SSN pattern)

Step 5 — Browser SDK URL Filtering

Use denyUrls and allowUrls to control which scripts generate captured errors:

Sentry.init({
  dsn: process.env.SENTRY_DSN,

  // Ignore errors from third-party scripts
  denyUrls: [
    /extensions\//i,           // Browser extensions
    /^chrome:\/\//i,           // Chrome internal
    /^chrome-extension:\/\//i, // Chrome extensions
    /^moz-extension:\/\//i,    // Firefox extensions
    /graph\.facebook\.com/i,   // Facebook SDK
    /connect\.facebook\.net/i, // Facebook SDK
    /cdn\.jsdelivr\.net/i,     // CDN-hosted third-party
  ],

  // Only capture errors from your own code
  allowUrls: [
    /https?:\/\/(www\.)?example\.com/i,
    /https?:\/\/staging\.example\.com/i,
  ],
});

Also configure Allowed Domains in Project Settings > Client Keys (DSN) > Configure to prevent unauthorized origins from sending events to your DSN:

example.com
*.example.com
staging.example.com

Step 6 — CSP Reporting via Sentry

Sentry can ingest Content-Security-Policy violation reports. Use the Security Headers endpoint (not the main DSN):

# Find the report URI in Project Settings > Security Headers
# Format: https://o<org-id>.ingest.us.sentry.io/api/<project-id>/security/?sentry_key=<public-key>

Add to your CSP header:

Content-Security-Policy: default-src 'self'; script-src 'self'; report-uri https://o123456.ingest.us.sentry.io/api/789/security/?sentry_key=abc123

Or use the newer report-to directive:

Report-To: {"group":"sentry","max_age":86400,"endpoints":[{"url":"https://o123456.ingest.us.sentry.io/api/789/security/?sentry_key=abc123"}]}
Content-Security-Policy: default-src 'self'; report-to sentry

Step 7 — GDPR Data Deletion

Sentry supports right-to-erasure requests via API:

# Delete a specific issue and all its events
curl -X DELETE \
  -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" \
  "https://sentry.io/api/0/projects/$SENTRY_ORG/$SENTRY_PROJECT/issues/$ISSUE_ID/"

# Delete events by tag (find issues for a specific user first)
curl -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" \
  "https://sentry.io/api/0/projects/$SENTRY_ORG/$SENTRY_PROJECT/issues/?query=user.id:$USER_ID" \
  | jq '.[].id' \
  | xargs -I{} curl -X DELETE \
    -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" \
    "https://sentry.io/api/0/projects/$SENTRY_ORG/$SENTRY_PROJECT/issues/{}/"

For bulk deletion, use Organization Settings > Data Privacy > Data Removal Requests (Business/Enterprise plans).

Data retention settings: Organization Settings > Subscription > Event Retention — configure 30/60/90-day retention windows to auto-purge old data.

Step 8 — Auth Token Hygiene Checklist

# Scan codebase for leaked auth tokens
grep -rn "sntrys_" --include="*.ts" --include="*.js" --include="*.py" 

---

*Content truncated.*

When not to use it

  • When the application does not handle sensitive user data
  • When default Sentry settings are sufficient for compliance

Prerequisites

Sentry project with Owner or Admin role@sentry/node >= 8.x or @sentry/browser >= 8.xList of sensitive data patterns

Limitations

  • Requires manual definition of sensitive data patterns
  • beforeSend logic must be maintained as data structures evolve

How it compares

This provides proactive data protection at the source, preventing sensitive information from ever leaving the client environment.

Compared to similar skills

sentry-security-basics side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
sentry-security-basics (this skill)027dCautionIntermediate
security-header-generator59moCautionIntermediate
backend-security-coder244moNo flagsIntermediate
security-best-practices76moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

security-header-generator

Dexploarer

Generates security HTTP headers (CSP, HSTS, CORS, etc.) for web applications to prevent common attacks. Use when user asks to "add security headers", "setup CSP", "configure CORS", "secure headers", or "HSTS setup".

599

backend-security-coder

sickn33

Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.

2446

security-best-practices

openai

Perform language and framework specific security best-practice reviews and suggest improvements. Trigger only when the user explicitly requests security best practices guidance, a security review/report, or secure-by-default coding help. Trigger only for supported languages (python, javascript/typescript, go). Do not trigger for general code review, debugging, or non-security tasks.

732

dependency-auditor

alirezarezvani

Check dependencies for known vulnerabilities using npm audit, pip-audit, etc. Use when package.json or requirements.txt changes, or before deployments. Alerts on vulnerable dependencies. Triggers on dependency file changes, deployment prep, security mentions.

16

command-injection-testing

Ed1s0nZ

命令注入漏洞测试的专业技能和方法论

13

sentry-data-handling

jeremylongshore

Manage sensitive data properly in Sentry. Use when configuring PII scrubbing, data retention, GDPR compliance, or data security settings. Trigger with phrases like "sentry pii", "sentry gdpr", "sentry data privacy", "scrub sensitive data sentry".

04

Search skills

Search the agent skills registry