HTTP 头盔

轻松地为您的 web 应用程序添加 CSP 和其他安全头。

安装

# npm
npm i @mcansh/http-helmet

使用

使用 @mjackson/node-fetch-server 的基本示例

import * as http from "node:http";
import { createRequestListener } from "@mjackson/node-fetch-server";
import { createNonce } from "@mcansh/http-helmet/react";
import { createSecureHeaders } from "@mcansh/http-helmet";

let html = String.raw;

let handler = (request) => {
  let nonce = createNonce();
  let headers = createSecureHeaders({
    "Content-Security-Policy": {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", `'nonce-${nonce}'`],
    },
  });

  headers.append("content-type", "text/html");

  return new Response(
    html`
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="UTF-8" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0"
          />
          <title>Hello World</title>
        </head>
        <body>
          <h1>Hello World</h1>

          <script nonce="${nonce}">
            console.log("nonce configured");
          </script>

          <script>
            alert("nonce not configured");
          </script>
        </body>
      </html>
    `,
    { headers },
  );
};

let server = http.createServer(createRequestListener(handler));

server.listen(3000);

console.log("✅ app ready: https://127.0.0.1:3000");