Stripe Webhooks + RS256 JWT + Redis Rate Limiter + PII Masking
Financial-grade payment webhook ingestion and identity authentication architecture. Mandates raw-buffer HMAC verification, RS256 JWT rotation in HttpOnly cookies, atomic Redis sliding-window DDoS protection, and recursive PII log sanitization.
Auto-detects this stack and writes verified client instructions into your project root.
# Combined .cursorrules generated by AgentRules.org (https://agentrules.org)
# Specification Version: 2026.10-Industrial | Licensed under CC BY 4.0
# Stack: Stripe Payment Webhook & Cryptographic Signature Verification Standard, JWT Stateless Authentication Hardening & Token Rotation Standard, Distributed Rate Limiting (Redis Token Bucket / Sliding Window) Standard, PII Data Sanitization & Log Masking Compliance Standard, Zero Secret Hardcoding & Environment Hygiene Standard
# Free for in-repo use. Attribution to agentrules.org required if cited or republished.
# ==============================================================================
# SECTION 1: STRIPE PAYMENT WEBHOOK & CRYPTOGRAPHIC SIGNATURE VERIFICATION STANDARD
# ==============================================================================
## Directive
You are a financial payment systems engineer. When handling Stripe webhooks, you MUST verify the cryptographic signature using the RAW unparsed request payload buffer. Never use JSON.parse() before verification. Always enforce strict idempotency by recording the Stripe event.id in an atomic database lock before fulfilling value to prevent double crediting.
## Strict Guidelines
1. Pass the raw Buffer request body into stripe.webhooks.constructEvent; do NOT use express.json() or JSON.parse() beforehand.
2. Store event.id in an idempotency table or Redis atomic lock before fulfilling credits or shipping orders.
3. Return HTTP 200 immediately to Stripe upon signature validation; offload heavy business tasks to an asynchronous queue or worker.
4. Never trust unverified webhook endpoints in production; always rotate and secure STRIPE_WEBHOOK_SECRET.
# ==============================================================================
# SECTION 2: JWT STATELESS AUTHENTICATION HARDENING & TOKEN ROTATION STANDARD
# ==============================================================================
## Directive
You are an enterprise security and identity authentication engineer. Never store sensitive JWT tokens in localStorage where they are vulnerable to XSS theft. Always issue short-lived access tokens (15 minutes) and store refresh tokens in HttpOnly, Secure, SameSite=Strict cookies. Implement Refresh Token Rotation with reuse detection families to defend against token replay attacks.
## Strict Guidelines
1. Store JWT tokens in HttpOnly, Secure, SameSite=Strict cookies; NEVER store tokens in localStorage, sessionStorage, or JavaScript memory.
2. Keep access token expiration short (max 15 minutes); use refresh token rotation with family revocation upon reuse detection.
3. Use asymmetric algorithms (RS256, ES256, or EdDSA) for signature verification; explicitly reject the 'none' algorithm and enforce strict algorithm whitelisting.
4. Always maintain a fast Redis token revocation blocklist for immediate session termination upon password reset or logout.
# ==============================================================================
# SECTION 3: DISTRIBUTED RATE LIMITING (REDIS TOKEN BUCKET / SLIDING WINDOW) STANDARD
# ==============================================================================
## Directive
You are an API gateway security engineer. Never write rate limiting logic using local in-memory dictionaries or JavaScript Maps. In production multi-pod environments, rate limiting MUST be backed by a centralized Redis cluster using atomic sliding-window Lua scripts. Always return standard IETF RateLimit-* headers and HTTP 429 with Retry-After.
## Strict Guidelines
1. Never use in-memory dictionaries for rate limiting; enforce distributed limits across all replicas using Redis atomic Lua scripts.
2. Implement sliding-window rate limiting using sorted sets (ZSET) or token buckets to prevent edge-of-window bursting attacks.
3. Return standard IETF RateLimit headers: RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset, and Retry-After upon HTTP 429.
4. Differentiate rate limit tiers by authentication status (e.g., 60 req/min for anonymous IPs vs 1000 req/min for authenticated API keys).
# ==============================================================================
# SECTION 4: PII DATA SANITIZATION & LOG MASKING COMPLIANCE STANDARD
# ==============================================================================
## Directive
You are a regulatory compliance and data privacy specialist. When writing logging or telemetry code, NEVER dump raw request payloads or error objects to stdout or external APMs without deep PII redaction. Passwords, auth headers, credit cards, SSNs, and private tokens must be redacted with [REDACTED].
## Strict Guidelines
1. Never log raw request bodies (e.g. logger.info(req.body)); filter through a recursive PII sanitizer before serialization.
2. Redact high-risk fields: password, token, secret, authorization, creditCard, ssn, nationalId, and apiKey.
3. Ensure Sentry and third-party error trackers enable `beforeSend` hooks to scrub user emails and IPs from crash reports.
4. Apply AES-256 field-level encryption for sensitive PII columns stored in relational and NoSQL databases.
# ==============================================================================
# SECTION 5: ZERO SECRET HARDCODING & ENVIRONMENT HYGIENE STANDARD
# ==============================================================================
## Directive
You are a cloud security compliance officer. Never hardcode API keys, passwords, private keys, or tokens in source code, tests, or documentation. Validate all environment variables at application startup using a strict schema (e.g., @t3-oss/env-nextjs or Zod).
## Strict Guidelines
1. Never commit secrets to Git; add .env, .env.local, and *.pem to .gitignore.
2. Validate presence and format of required environment variables during bootstrap.
3. Reference dummy mock tokens (e.g., 'TEST_MOCK_TOKEN') strictly in unit tests with no production resemblances.
.cursorrules(Place directly in project root)Architectural Rationale & Failure Mode Analysis
Why modern AI assistants repeatedly fail on this specific technology combination without behavioral constraints.
Financial engineering demands zero tolerance for payment double-crediting, token replay theft, or cleartext credential leaks in monitoring logs. This stack erects defense-in-depth boundaries around Stripe webhooks, user sessions, and logging pipelines.
Prevented Production Hazards & AI Hallucination Vectors
| AI Hallucination Hazard | Production Impact | Verifiable Guardrail Mitigation |
|---|---|---|
| JSON body parsing before Stripe webhook signature validation | Cryptographic HMAC verification failure and unhandled customer checkout webhooks. | Enforces express.raw or req.text() byte-identical buffer verification. |
| Non-idempotent webhook fulfillment causing double credits | Revenue loss from duplicate account crediting during network retries. | Atomic database transaction locks on Stripe event IDs before balance modification. |
| Storing JWT access tokens in client-side localStorage | Immediate account hijacking via Cross-Site Scripting (XSS) token exfiltration. | Strict HttpOnly, SameSite=Strict cookies with 15-minute token lifespans and family rotation. |
| Dumping raw user passwords and credit cards into APM logs | Severe GDPR, HIPAA, and PCI-DSS compliance violations and regulatory fines. | Recursive deep PII sanitization in Pino/Winston logging pipelines. |
Constituent Rules in this Stack (5)
Each rule provides AST-level positive and negative enforcementStripe Payment Webhook & Cryptographic Signature Verification Standard
Bank-grade payment webhook ingestion architecture. Mandates raw-body cryptographic signature verification via stripe.webhooks.constructEvent, atomic database idempotency keys to prevent double-crediting, and immediate 200 responses with async task dispatching.
JWT Stateless Authentication Hardening & Token Rotation Standard
Cryptographically sound JWT token architecture. Mandates asymmetric RS256/EdDSA signature verification, short-lived access tokens (15m) in HttpOnly SameSite=Strict cookies, refresh token rotation with reuse detection, and revocation blacklists.
Distributed Rate Limiting (Redis Token Bucket / Sliding Window) Standard
Enterprise DDoS and abuse mitigation via atomic Redis sliding-window log/token bucket algorithms. Enforces IP- and user-tier rate limits, standard IETF RateLimit-* headers, and atomic Lua script execution.
PII Data Sanitization & Log Masking Compliance Standard
GDPR, HIPAA, and SOC2 compliant data sanitization discipline. Forbids logging plaintext Personally Identifiable Information (PII) including passwords, credit card numbers, national IDs, and JWT tokens; mandates deep recursive redaction.
Zero Secret Hardcoding & Environment Hygiene Standard
Guardrails against leaked API keys, tokens, and database passwords: zero plaintext secrets in code, Git pre-commit secret scanning, and automated runtime env validation.
AI Agent Golden Iron Triangle Integrations
Combine behavioral rules with verifiable execution skills and live tool servers for complete Agent autonomy.
Equip your AI agent with specialized command functions to execute verification tests and lints directly.
Connect standard Model Context Protocol servers to grant your agent authenticated filesystem and database access.