npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@arraypress/security-headers

v3.0.0

Published

Security response headers for static hosts — CSP, HSTS, X-Frame-Options, Referrer-Policy, Permissions-Policy. Generates a Cloudflare/Netlify _headers file, with a strict, hash-based CSP derived from the finished build. Zero dependencies, no framework.

Readme

@arraypress/security-headers

Security response headers for static hosts — CSP, HSTS, X-Frame-Options, Referrer-Policy, Permissions-Policy. Generates a Cloudflare/Netlify _headers file, with a strict, hash-based CSP derived from the finished build. Zero dependencies, no framework.

Using Astro? You want @arraypress/seo-astro. Its seo() integration writes _headers with this package at the end of every build, CSP hashes included, alongside the rest of what a site needs to be found. Everything below about csp: 'auto' applies there too.

Install

npm install @arraypress/security-headers

A static build

// after your build has written dist/
import { writeHeadersFile } from '@arraypress/security-headers/write';

const { notes } = writeHeadersFile('dist');
for (const n of notes) console[n.level === 'warn' ? 'warn' : 'log'](n.message);

It reads the finished pages, derives the CSP and writes dist/_headers:

CSP from 50 pages — 5 inline script hashes, 8 inline style hashes, 1 third-party origin (https://fonts.googleapis.com)
wrote _headers — 8 headers on /*

What csp: 'auto' does

It scans every built .html file and writes one site-wide policy:

  • Hashes every inline <script> and <style>, so script-src needs no 'unsafe-inline' — the theme flash-guard, a define:vars block and a component's inline styles all keep working. JSON-LD isn't hashed; data blocks don't execute.
  • Allows exactly the third-party origins the pages load from: script and stylesheet URLs, font preloads, iframes, form actions, media. Including scripts an inline loader injects (createElement('script') + .src = '…', the pattern analytics snippets use), which never appear as a tag in the HTML.
  • Adds the hosts known providers talk back to that the page never names: Google Fonts' fonts.gstatic.com, GA4's collection hosts, Cloudflare Web Analytics, Simple Analytics, GoatCounter, Umami Cloud, Turnstile's frame. Every third-party script origin also gets connect-src — a script you already run can reach its own origin anyway — which covers any tracker that beacons home, self-hosted ones included.
  • Allows style="" attributes (style-src-attr 'unsafe-inline'). Hashes can't cover attributes, every component-driven site has them, and an attribute can't run script.

So turning on an analytics provider or pointing a form at Formspree needs no CSP edit: rebuild, and it's in the policy.

Hosts that only exist at runtime: data-csp

The scan reads HTML, so it can't see a URL a script builds after the page loads — a video player that sets its iframe src on click, a live follower count that fetches an API. The component that does it declares the host on its own element instead:

<section data-csp="frame-src https://www.youtube-nocookie.com">…</section>
<div data-csp="connect-src https://api.github.com https://public.api.bsky.app">…</div>

The declaration sits next to the code that needs it, so the two can't drift, and only pages that render the component widen the policy. Values are plain https:// origins (a leading *. is allowed) or a whole scheme, for the one page that needs it:

<div data-csp="media-src blob:">…</div>          <!-- a player that builds its audio in the page -->
<div data-csp="img-src data:; connect-src wss:">…</div>

The schemes accepted are https:, wss:, blob:, data: and mediastream:. blob: and data: are refused in script-src, where they'd let injected markup run code. Keywords such as 'unsafe-inline', paths, http: and unknown directives are refused too, and the build lists anything it ignored.

What neither the scan nor a component can know, you add. Arrays you pass are the base and the scan's findings go on top:

writeHeadersFile('dist', {
  csp: { auto: true, connectSrc: ["'self'", 'https://api.example.com'] },
})

Trial it before enforcing with cspReportOnly: 'auto', which sends the same policy as Content-Security-Policy-Report-Only.

One policy for the site, not one per page

Astro's own CSP is a per-page <meta> tag, and it doesn't support <ClientRouter />. The router swaps pages in without a reload, so the policy the visitor's first page arrived with must cover the inline code of every page they reach after it — a per-page policy can't. 'auto' unions the hashes across the whole build into one header, so a soft navigation never lands on code the policy doesn't know. It also runs as a real HTTP header, which a <meta> CSP can't fully replace (frame-ancestors is ignored in <meta>).

If you're not using the router, Astro's security.csp is a fine choice: set csp: false here and this writes everything else.

What a hash policy blocks

Two things no hash can allow. The build warns if it finds either, because in the browser they fail silently:

  • inline event handlers — onclick="…". Move them into a script.
  • href="javascript:…" links.

The scan reads each tag whole, so markup quoted inside an attribute — a code sample in data-code="<script>…</script>", a snippet showing onplay={…} — is the attribute's text, not a script to hash or a handler to warn about. Comments are skipped, and so is anything inside a <textarea>.

Keeping a big site under the line limit

The CSP is one _headers line and Cloudflare caps a line at 2,000 characters, so what matters is how many DISTINCT inline blocks the build emits. Measured on a 241-page store theme: 90 inline scripts and 27 inline styles, a 6,732-char line. Two changes took it to 13 and 9, and 1,621:

  • vite: { build: { assetsInlineLimit: 0 } } — Astro inlines small bundled scripts and stylesheets, each its own hash. This emits them as cacheable files instead.

  • Pass per-page data through an attribute, not define:vars. define:vars writes the value into the script text, so a product slug makes every product page a new hash. Read it from the element instead and the text is identical everywhere:

    <script is:inline data-slug={product.id}>
      const slug = document.currentScript.dataset.slug;
    </script>

Libraries that need a nudge

  • Anything that injects <style> elements at runtime is blocked. ApexCharts does by default: set chart: { injectStyleSheet: false } and import apexcharts/dist/apexcharts.css (+ apexcharts-legend.css) yourself.
  • WebAssembly needs 'wasm-unsafe-eval' — Pagefind's search, for one. It allows compiling wasm, not JavaScript eval(), and it's a keyword, so it belongs in your config (scriptSrc: ["'self'", "'wasm-unsafe-eval'"]), not in a data-csp declaration, which only accepts hosts and schemes.

Limits

  • Cloudflare caps each _headers line at 2,000 characters, and the CSP is one line. Each hash costs ~54. The build warns past the limit; the usual fix is build.inlineStylesheets: 'never', which moves component CSS out of inline <style> blocks into files.
  • Vercel doesn't read _headers. Cloudflare Pages and Netlify do.
  • A URL that redirects to another host is blocked at the redirect. The scan allows the host written in the HTML; CSP checks every hop. Link the final host directly — e.g. maps.google.com/maps?…&output=embed 301s to www.google.com, so embed www.google.com/maps?… instead.
  • A _headers already in the build (copied from public/) is kept and this is appended to it. If both set the same header, the build says so — both would be sent.

Why a file and not middleware

On Cloudflare, a static-assets deploy with no server script serves requests for free. Adding middleware to set headers adds a script and makes every request billable. _headers is applied at the edge for nothing.

Options

writeHeadersFile(dir, config?, options?)

  • config — a SecurityHeadersConfig (below), where csp and cspReportOnly also accept 'auto' or { auto: true, … }. csp defaults to 'auto' here.
  • options.path — path pattern the headers apply to. Default '/*'.
  • options.filename — output name. Default '_headers'.
  • options.scan — a scan you've already made of the build, so the pages aren't read twice. Read from dir when omitted.

It returns { file, body, headers, notes }; notes is what to show the person building, each { level: 'info' | 'warn', message }. Nothing is logged for you.

Cloudflare caps a _headers file at 100 rules; one path costs one rule however many headers it carries.

The scanner on its own

@arraypress/security-headers/scan is the machinery underneath, for a build that wants the policy without the file:

import { scanDir, autoCsp } from '@arraypress/security-headers/scan';
import { headersFile } from '@arraypress/security-headers';

const csp = autoCsp(scanDir('dist'));
writeFileSync('dist/_headers', headersFile({ csp }));

scanHtml(html), mergeScans(scans), hashSource(text) and the PROVIDERS table are exported too. Node only.

Anywhere else

The generators are plain functions with no framework attached — use them from a build script, a Worker, or a test.

import { headersFile, buildHeaders, buildCSP, buildHSTS } from '@arraypress/security-headers';

// A _headers file, as a string.
writeFileSync('dist/_headers', headersFile({ csp: { scriptSrc: ["'self'"] } }));

// The same values as a plain object — for a Response you build yourself.
return new Response(body, { headers: buildHeaders() });

// Or one header at a time.
buildCSP({ defaultSrc: ["'self'"] });
buildHSTS({ maxAge: 31536000, includeSubDomains: true });

headersFile() renders the Cloudflare/Netlify format — a path line, then each header indented two spaces:

/*
  X-Content-Type-Options: nosniff
  X-Frame-Options: SAMEORIGIN
  Referrer-Policy: strict-origin-when-cross-origin
  Permissions-Policy: camera=(), microphone=(), geolocation=()
  Cross-Origin-Opener-Policy: same-origin
  X-Permitted-Cross-Domain-Policies: none
  Content-Security-Policy: default-src 'self'; script-src 'self'; …
  Strict-Transport-Security: max-age=31536000

headersFile() doesn't read a build, so its CSP is the strict default policy unless you pass one. writeHeadersFile() derives it from the build instead.

Configuration

| Option | Default | Notes | |---|---|---| | csp | strict defaults | CSPConfig or false. writeHeadersFile() also takes 'auto', its default. | | cspReportOnly | false | A stricter policy sent as …-Report-Only, to trial before enforcing. | | hsts | true | HSTSConfig, true for defaults (a year, this host only), or false to skip. | | xContentTypeOptions | true | Emits nosniff. | | xFrameOptions | 'SAMEORIGIN' | 'DENY', 'SAMEORIGIN' or false. | | referrerPolicy | 'strict-origin-when-cross-origin' | Any policy string, or false. | | permissionsPolicy | camera=(), microphone=(), geolocation=() | Any policy string, or false. | | crossOriginOpenerPolicy | 'same-origin' | Use 'same-origin-allow-popups' for OAuth popups. | | crossOriginEmbedderPolicy | false | 'require-corp' / 'credentialless'. See isolation below. | | crossOriginResourcePolicy | false | 'same-origin' / 'same-site' / 'cross-origin'. | | permittedCrossDomainPolicies | 'none' | Legacy Flash/Acrobat crossdomain.xml opt-out. | | originAgentCluster | false | Emits Origin-Agent-Cluster: ?1. | | reportingEndpoints | null | { csp: 'https://…' } → Reporting-Endpoints. |

Every header is independently togglable — pass false to skip it.

Cross-origin isolation

Cross-Origin-Opener-Policy is on by default: it severs window.opener across origins and needs nothing from the resources you load, so it costs you nothing. The one gotcha is OAuth popups that talk back via window.opener — those want 'same-origin-allow-popups'.

Cross-Origin-Embedder-Policy and Cross-Origin-Resource-Policy are off by default, deliberately. COEP blocks every cross-origin resource that hasn't opted in, and CORP stops other sites embedding your images and fonts. Turn them on together, with COOP 'same-origin', when you actually need crossOriginIsolated — that is, SharedArrayBuffer or wasm threads:

buildHeaders({
  crossOriginOpenerPolicy: 'same-origin',
  crossOriginEmbedderPolicy: 'require-corp',
  crossOriginResourcePolicy: 'same-origin',
})

An app using AudioWorklets or Workers does not need this on its own — only shared memory does.

Rolling out a CSP

Send a strict policy as report-only alongside a permissive enforced one, watch the reports, then promote it:

buildHeaders({
  csp: { scriptSrc: ["'self'", "'unsafe-inline'"] },   // enforced today
  cspReportOnly: { scriptSrc: ["'self'"] },             // the goal
  reportingEndpoints: { csp: 'https://example.com/csp-report' },
})

CSP directives are camelCase and become kebab-case on the wire: defaultSrc, scriptSrc, styleSrc, imgSrc, fontSrc, connectSrc, frameSrc, and the rest.

buildHeaders({
  csp: { scriptSrc: ["'self'", 'https://challenges.cloudflare.com'] },
  xFrameOptions: 'DENY',
  hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },
  permissionsPolicy: false,
});

Gotchas

Two defaults are strict on purpose and will bite if your site is the exception. Both fail silently in the browser, so they're worth knowing before you deploy.

The microphone and camera are off

Permissions-Policy defaults to camera=(), microphone=(), geolocation=(), which disables getUserMedia() outright — the call rejects, and nothing in your own code looks wrong. Right for a marketing or directory site; wrong for an app that records audio.

// An app with a record-from-mic button:
buildHeaders({ permissionsPolicy: 'camera=(), microphone=(self), geolocation=()' })

The default CSP blocks Google Fonts

font-src defaults to 'self' and style-src to 'self' 'unsafe-inline', so a <link> to fonts.googleapis.com and the files it pulls from fonts.gstatic.com are both blocked:

buildHeaders({
  csp: {
    styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
    fontSrc: ["'self'", 'https://fonts.gstatic.com'],
  },
})

The same applies to any third-party origin — analytics, embeds, a CDN. The default assumes a site that serves everything itself; add origins as you add dependencies rather than loosening default-src.

Under csp: 'auto' this one doesn't arise — the scan finds the stylesheet and adds fonts.gstatic.com itself.

Security notes

X-Frame-Options is superseded by CSP's frame-ancestors but is still emitted for older browsers — they don't cost each other anything.

The Permissions-Policy default is a tight baseline suited to admin surfaces. If your site legitimately uses the camera, microphone or geolocation, extend it rather than dropping the header.

HSTS only takes effect over HTTPS. By default it covers this host alone: includeSubDomains would hold every subdomain to HTTPS for a year too, and one site's headers can't know what else lives on the domain. Turn it on once every host under the domain serves HTTPS:

hsts: { includeSubDomains: true }

preload goes further, and is a one-way door: browsers ship the list, so leaving it takes months. Submit to hstspreload.org only when you're sure.

Licence

MIT © ArrayPress Limited