Use Cases (अपडेट: 2/6/2026)

Claude Code से Web Security Headers सेट करें: CSP, nonce, HSTS और ads-safe rollout

Claude Code से CSP, nonce, HSTS, frame-ancestors और security headers लागू करें।

Claude Code से Web Security Headers सेट करें: CSP, nonce, HSTS और ads-safe rollout

Web security headers छोटे HTTP response headers हैं, लेकिन उनका असर बड़ा होता है। ये browser को बताते हैं कि कौन सा script चल सकता है, कौन आपकी admin page को iframe में embed कर सकता है, बाहर जाते समय referrer URL कितना भेजना है, और camera, microphone, geolocation जैसी browser permissions खुली रहेंगी या बंद।

Claude Code इस काम में तेज मदद कर सकता है। वह repository पढ़ सकता है, third-party scripts ढूंढ सकता है, framework config बदल सकता है और verification commands बना सकता है। लेकिन prompt अगर vague हो तो वह dangerous shortcut भी दे सकता है। उदाहरण के लिए, “CSP error ठीक करो” कहने पर वह script-src * 'unsafe-inline' 'unsafe-eval' जैसी policy सुझा सकता है। Console error बंद हो जाएगी, पर CSP की सुरक्षा भी कमजोर हो जाएगी।

इस guide में 2026-06 के हिसाब से practical तरीका है: पहले resource inventory, फिर Content-Security-Policy-Report-Only, फिर reports देखकर policy को narrow करना, और अंत में enforce करना। हम CSP, nonce, HSTS, X-Frame-Options, frame-ancestors, Referrer-Policy, Permissions-Policy, Next.js, Astro, Express, Cloudflare Pages, CSP report, Security Headers, CSP Evaluator, Google Analytics, GTM, AdSense और image CDN conflicts कवर करेंगे। Claude Code की broader safety के लिए Claude Code security best practices और security audit guide भी देखें।

Official references साथ रखें: MDN Content-Security-Policy, Next.js CSP guide, MDN Strict-Transport-Security, hstspreload.org, Cloudflare Pages Headers, Helmet, Google Tag Manager CSP, और AdSense CSP guide

पहले inventory कराएं

Security header copy-paste करने से पहले Claude Code से पूछें कि site सच में क्या load कर रही है।

इस repository के लिए Web security headers design करें।
Rules:
- पहले script, style, image, font, frame, connect origins की list बनाएं।
- CSP पहले Report-Only mode में हो।
- * और permanent unsafe-inline avoid करें।
- Next.js nonce से dynamic rendering/cache पर क्या असर पड़ेगा, लिखें।
- Google Analytics, GTM, AdSense, image CDN, YouTube iframe conflicts check करें।
- curl, Security Headers, CSP Evaluator verification steps दें।

कुछ terms आसान भाषा में समझें। CSP browser की allowlist है। nonce हर response का one-time password है। HSTS browser को याद दिलाता है कि आगे HTTPS ही use करना है। frame-src बताता है आपकी page कौन से iframe load कर सकती है। frame-ancestors बताता है आपकी page को कौन iframe में डाल सकता है। Clickjacking protection के लिए frame-ancestors ज्यादा important है।

Headerअच्छा starting pointसावधानी
Content-Security-Policyपहले Content-Security-Policy-Report-Only* से problem hide न करें
Strict-Transport-Securitymax-age=300; includeSubDomains से शुरू करेंpreload तभी जब सभी subdomains HTTPS-ready हों
X-Frame-OptionsDENY या SAMEORIGINmodern control के लिए frame-ancestors
Referrer-Policystrict-origin-when-cross-originURL में token या personal data न रखें
Permissions-Policyunused features बंद करेंसिर्फ required features allow करें
X-Content-Type-Optionsnosniffusually पूरे site पर safe

HSTS preload को default मत बनाएं। official preload site gradual rollout बोलती है, क्योंकि preload हटाने में समय लग सकता है। एक पुराना HTTP-only subdomain भी users के लिए outage बन सकता है।

CSP rollout flow

एक safe CSP rollout ऐसा दिखता है:

flowchart LR
  A["Resource inventory"] --> B["Report-Only CSP"]
  B --> C["Browser console और reports"]
  C --> D["Ads, analytics, CDN, iframe, noise classify"]
  D --> E["Nonce या hash based CSP"]
  E --> F["Security Headers और CSP Evaluator"]

Reports में जो domain दिखे, उसे तुरंत allow न करें। Browser extensions, corporate proxy, old tags और attack attempts भी report बना सकते हैं। Claude Code से classification कराएं, लेकिन final decision product need पर लें।

Next.js में nonce CSP

Next.js App Router documentation अब proxy.ts में per-request nonce दिखाती है। पुराने projects में middleware.ts दिख सकता है। Concept same है: random nonce बनाएं, request header में डालें, और वही CSP में use करें।

Nonce का मतलब dynamic rendering हो सकता है। Static blog या landing page में hash-based CSP या external scripts बेहतर हो सकते हैं। Login, checkout, account और admin pages में nonce ज्यादा useful है।

// proxy.ts
import { NextRequest, NextResponse } from "next/server";

export function proxy(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
  const isDev = process.env.NODE_ENV !== "production";

  const csp = [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic' ${isDev ? "'unsafe-eval'" : ""} https: http:`,
    `style-src 'self' ${isDev ? "'unsafe-inline'" : `'nonce-${nonce}'`} https://fonts.googleapis.com`,
    "font-src 'self' https://fonts.gstatic.com",
    "img-src 'self' data: blob: https:",
    "connect-src 'self' https://www.google-analytics.com https://analytics.google.com",
    "frame-src 'self' https://www.youtube-nocookie.com",
    "object-src 'none'",
    "base-uri 'self'",
    "form-action 'self'",
    "frame-ancestors 'none'",
    "upgrade-insecure-requests",
    "report-uri /api/csp-report",
  ].join("; ").replace(/\s{2,}/g, " ").trim();

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-nonce", nonce);

  const response = NextResponse.next({ request: { headers: requestHeaders } });
  response.headers.set("Content-Security-Policy", csp);
  response.headers.set("X-Content-Type-Options", "nosniff");
  response.headers.set("X-Frame-Options", "DENY");
  response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
  response.headers.set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(self)");
  response.headers.set("Strict-Transport-Security", "max-age=300; includeSubDomains");
  return response;
}

export const config = {
  matcher: ["/((?!api/csp-report|_next/static|_next/image|favicon.ico).*)"],
};

GTM use करते हैं तो nonce snippet या component तक pass करें। GTM bootstrap inline JavaScript है, इसलिए Google nonce approach recommend करता है। AdSense भी strict CSP guide देता है, क्योंकि ad domains बदल सकते हैं। Static allowlist revenue break कर सकती है।

CSP report endpoint

Report-Only तभी useful है जब reports collect हों।

// app/api/csp-report/route.ts
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
  const contentType = request.headers.get("content-type") ?? "";
  const body = await request.text();

  const isReport =
    contentType.includes("application/csp-report") ||
    contentType.includes("application/reports+json") ||
    body.includes("violated-directive");

  if (!isReport) {
    return NextResponse.json({ ok: false }, { status: 415 });
  }

  console.warn("csp-report", body.slice(0, 4000));
  return new NextResponse(null, { status: 204 });
}

Production में full URL store न करें अगर query में personal data हो सकता है। Route, violated directive, blocked URI, user agent, time और count काफी हैं। report-uri पुराना है, पर compatibility के लिए useful है। report-to add कर सकते हैं, लेकिन केवल उसी पर depend न करें।

Astro, Express और Cloudflare

Astro में fixed headers middleware से आसानी से लगते हैं। Mostly static site में inline scripts कम करना nonce से आसान हो सकता है।

// src/middleware.ts
import { defineMiddleware } from "astro:middleware";

const securityHeaders: Record<string, string> = {
  "Content-Security-Policy-Report-Only": "default-src 'self'; script-src 'self' https://www.googletagmanager.com; img-src 'self' data: blob: https:; connect-src 'self' https://www.google-analytics.com; frame-src 'self' https://www.youtube-nocookie.com; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; report-uri /api/csp-report",
  "X-Content-Type-Options": "nosniff",
  "X-Frame-Options": "DENY",
  "Referrer-Policy": "strict-origin-when-cross-origin",
  "Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=(self)",
};

export const onRequest = defineMiddleware(async (_context, next) => {
  const response = await next();
  for (const [name, value] of Object.entries(securityHeaders)) {
    response.headers.set(name, value);
  }
  return response;
});

Express में Helmet practical है, लेकिन CSP app-specific रखनी होगी।

import crypto from "node:crypto";
import express from "express";
import helmet from "helmet";

const app = express();

app.use((req, res, next) => {
  res.locals.cspNonce = crypto.randomBytes(16).toString("base64");
  next();
});

app.use(helmet({
  contentSecurityPolicy: {
    useDefaults: false,
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`, "'strict-dynamic'", "https:", "http:"],
      imgSrc: ["'self'", "data:", "blob:", "https:"],
      connectSrc: ["'self'", "https://www.google-analytics.com"],
      objectSrc: ["'none'"],
      baseUri: ["'self'"],
      frameAncestors: ["'none'"],
      reportUri: ["/csp-report"],
    },
  },
  strictTransportSecurity: { maxAge: 300, includeSubDomains: true },
  referrerPolicy: { policy: "strict-origin-when-cross-origin" },
  xFrameOptions: { action: "deny" },
}));

Cloudflare Pages _headers static headers के लिए अच्छा है, लेकिन per-request nonce नहीं बना सकता।

/*
  X-Content-Type-Options: nosniff
  X-Frame-Options: DENY
  Referrer-Policy: strict-origin-when-cross-origin
  Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(self)
  Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' https://www.googletagmanager.com; img-src 'self' data: blob: https:; connect-src 'self' https://www.google-analytics.com; frame-src 'self' https://www.youtube-nocookie.com; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; report-uri /csp-report

Use cases और common pitfalls

Content site में GA4, GTM, AdSense, fonts, YouTube और image CDN साथ होते हैं। CSP enforce करने से पहले ads render, Analytics events और images check करें। Perfect score से ज्यादा important revenue path का काम करते रहना है।

SaaS admin area में third-party scripts कम रखें। frame-ancestors 'none', object-src 'none', base-uri 'self', narrow form-action good baseline है। Payment SDK और support chat केवल required routes पर allow करें।

Embeddable widget अलग policy चाहता है। अगर customer sites iframe में आपकी page embed करेंगी, उस route पर X-Frame-Options: DENY गलत है। Route-specific headers और trusted frame-ancestors use करें।

Verification और tested result

कम से कम home, login/form, और embed/checkout route check करें।

curl -I https://example.com/
curl -I https://example.com/login
curl -I https://example.com/embed/widget

फिर Security Headers से overall scan और CSP Evaluator से CSP weaknesses देखें। Score useful है, लेकिन final goal है: security बढ़े और ads, analytics, payment, images, iframe न टूटें।

इस article के test setup में Report-Only सबसे useful step निकला। GTM nonce issue, GA4 connect-src, YouTube frame-src, और CDN img-src अलग-अलग reports में दिखे। Claude Code से classification कराने पर सिर्फ domains जोड़ने के बजाय route-based CSP, nonce passing, unused tags removal और gradual HSTS rollout plan मिला। Real repository में इसे लागू करना हो तो Claude Code training and consultation या ClaudeCodeLab products से checklist को CLAUDE.md review rule में बदलें।

#Claude Code #security #HTTP headers #CSP #web development
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.