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

@astral/csp-header

v1.0.3

Published

Библиотека для генерации Content Security Policy (CSP) заголовков и их инжектирования в nginx config. Позволяет централизованно обновлять набор доменов и политик для CSP.

Readme

@astral/csp-header

Библиотека для генерации Content Security Policy (CSP) заголовков и их инжектирования в nginx config. Позволяет централизованно обновлять набор доменов и политик для CSP.

Основные возможности

  • Генерация CSP заголовков на основе набора инструкций.
  • Готовые наборы инструкций для сервисов, используемых в компании.
  • Инструменты для вставки заголовков в конфигурацию Nginx.

Базовое использование

.deploy/nginx.conf

http {
  server {
    location / {
      alias /usr/share/nginx/html/;
      index index.html;

      add_header X-Frame-Options SAMEORIGIN;
      add_header Content-Security-Policy "Сгенерируется при билде c помощью .scripts/generateCsp";
    }
  }
}

.scripts/generateCsp.mjs

import path from 'node:path';
import {
  astralFrontendStaticInstruction,
  astralIdentityInstruction,
  coreInstruction,
  generateCsp,
  injectToNginxConfig,
  sentryInstruction,
  uxFeedbackInstruction,
  yandexMetrikaInstruction,
} from '@astral/csp-header';

const csp = generateCsp({
  instructions: [
    coreInstruction,
    astralFrontendStaticInstruction,
    uxFeedbackInstruction,
    yandexMetrikaInstruction,
    sentryInstruction,
    astralIdentityInstruction,
  ],
  // При возникновении блокировки ресурса CSP будет отправлен отчет в sentry
  reportUrl:
    'https://sentry.infra.yandex.astral-dev.ru/api/000/security/?sentry_key=123',
});

injectToNginxConfig({
  csp,
  nginxConfigPath: path.resolve('.deploy', '.nginx', 'nginx.conf'),
});

.deploy/Dockerfile

# BUILD
RUN npm run build
RUN node ./.scripts/production/generateCSP.mjs

FROM harbor.infra.yandex.astral-dev.ru/proxy-hub.docker.com/fholzer/nginx-brotli:v1.28.0

COPY --from=build /usr/src/app/apps/demo/.deploy/.nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=build /usr/src/app/apps/demo/dist /usr/share/nginx/html

Пример в project-starter

Готовые инструкции

coreInstruction

Разрешено:

  • Собственный домен (self): Загрузка любого контента (скрипты, стили, картинки, шрифты), а также запросы (fetch/XHR) и WebSocket-соединения (ws/wss) ТОЛЬКО с текущим доменом.
  • Скрипты: Инлайн-скрипты (<script>...</script>) и динамический код через eval().
  • Стили: Инлайн-стили (атрибуты style="..." и теги <style>).
  • Изображения: Загрузка изображений со своего домена и через data: URI.
  • Воркеры и фреймы: Запуск Web Workers и загрузка фреймов (iframe) со своего домена + через blob: URL.
  • Объекты: Загрузка плагинов (например, <object>) только со своего домена.

Запрещено:

  • Встраивание текущего сайта в iframe: Встраивать сайт в iframe разрешено только на текущем домене. Приоритетнее X-Frame-Options заголовка

Генерируемое значение заголовка:

default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'self'; worker-src 'self' blob:; frame-src 'self' blob:; frame-ancestors 'self'; child-src 'self' blob:; object-src 'self';

yandexMetrikaInstruction

Разрешает загрузку скриптов счетчиков, отправку аналитики, сбор данных для Яндекс.Метрика через https и WebSocket. Логирование кликов, локальные порты вебвизора и отображение во фреймах на доменах yandex. Содержит большой набор доменов, указанных на сайте yandex.


sentryInstruction

Добавляет разрешение на отправку запросов в https://sentry.infra.yandex.astral-dev.ru/.


googleRecaptchaInstruction

Разрешает скрипты капчи, фреймы проверки и статические изображения gstatic.


telegramInstruction

Разрешает загрузку аватарок пользователей, скрипты и сетевые запросы к доменам Telegram.


uxFeedbackInstruction

Разрешает скрипты, стили, шрифты Google Fonts, изображения и сетевые соединения для поддоменов uxfeedback.ru.


astralIdentityInstruction

Разрешает загрузку изображений/иконок и сетевые запросы для продакшн и dev/stage стендов identity.


astralFrontendStaticInstruction

Разрешает загрузку скриптов, стилей, картинок, шрифтов и работу Web Workers из https://frontend-static.astral.ru/.


cryptoPluginsInstruction

Поддержка плагинов для работы с ЭЦП (Рутокен, JaCarta). Разрешает загрузку локального скрипта JaCarta WebClient, API Рутокен и сетевое взаимодействие с локальным портом 24738.


dadataInstruction

Разрешает запросы для https://suggestions.dadata.ru.


googleFontsInstruction

Разрешает импорт стилей и шрифтов из Google Fonts и CDNJS.

Кастомные инструкции

import {
  generateCsp,
  yandexMetrikaInstruction,
  CSP_VALUES,
} from '@astral/csp-header';

const customCoreInstruction = {
  'default-src': [CSP_VALUES.self],
  'script-src': [
    CSP_VALUES.self,
    CSP_VALUES.unsafeInline,
    CSP_VALUES.unsafeEval,
  ],
  'img-src': [CSP_VALUES.self, CSP_VALUES.data, CSP_VALUES.blob],
  'object-src': [CSP_VALUES.none],
};

const myApiInstruction = {
  'script-src': ['https://myapi.ru'],
};

const csp = generateCsp({
  instructions: [
    customCoreInstruction,
    myApiInstruction,
    yandexMetrikaInstruction,
  ],
});

Расширение coreInstruction

import {
  generateCsp,
  coreInstruction,
} from '@astral/csp-header';

const extendsCoreInstruction = {
  // coreInstruction для img-src содержит: 'img-src': [CSP_VALUES.self, CSP_VALUES.data]
  // Результирующий header будет содержать 'img-src': [CSP_VALUES.self, CSP_VALUES.data, CSP_VALUES.blob]
  'img-src': [CSP_VALUES.blob],
};

const csp = generateCsp({
  instructions: [
    coreInstruction,
    extendsCoreInstruction,
  ],
});

reportUrl. Получение уведомлений о блокировке ресурсов

Рекомендуется настраивать reportUrl для отправки сообщений в sentry. Сообщения могут указывать на неправильно настроенный CSP.

Принцип работы

generateCsp

generateCsp делает merge для всех instructions и удаляет дубли.

Интеграция если уже настроен CSP в nginx

Если вы интегрируете пакет и у вас уже настроен CSP обязательно сверьте ваш текущий заголовок и сгенерированный.