@neon-pixels/security 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -72,6 +72,122 @@ const { headers } = nuxtReportOnlyPolicy({
72
72
 
73
73
  Returns `{ policy, headers }`. `headers` holds `Content-Security-Policy-Report-Only` (and `Reporting-Endpoints` when `reportEndpoint` is set). The policy allows Clerk, Cloudflare Turnstile, Sentry, optionally Google Analytics, and `'unsafe-inline'` scripts for Nuxt's inline payload. It only reports; whether to enforce it, and how to move off `'unsafe-inline'`, is up to the app.
74
74
 
75
+ ### Enforcing in Nuxt
76
+
77
+ `nuxtPolicy` is the enforced counterpart of the report-only preset. It shares its Clerk, Sentry, Turnstile, and Google Analytics source lists with the report-only preset, but scripts need a per-response nonce instead of `'unsafe-inline'`, and it has no `'unsafe-eval'`. It is narrower than the report-only preset: it has no `blob:` script source, no Clerk bot-protection origins, and no `manifest-src`.
78
+
79
+ ```ts
80
+ import { nuxtPolicy } from "@neon-pixels/security";
81
+
82
+ const { policy, headers } = nuxtPolicy({
83
+ clerkPublishableKey,
84
+ sentryDsn,
85
+ analytics: true,
86
+ reportEndpoint: "/csp-report",
87
+ nonce, // from nonceForContext(event.context)
88
+ development: import.meta.dev,
89
+ });
90
+ ```
91
+
92
+ Returns `{ policy, directives, headers }`. `headers` holds `Content-Security-Policy` (and `Reporting-Endpoints` when `reportEndpoint` is set). Without a `nonce` the policy is still valid and allows no inline script, which is the right policy for responses that are not rendered pages. `development: true` also allows `'unsafe-eval'` scripts, `ws:` and `wss:` connections, and `'self'` frames for the Nuxt dev server, and nothing else. `nuxtPolicy`, `addNonceToScripts`, and `addNonceToScriptTags` throw a `TypeError` for a nonce that is not base64.
93
+
94
+ To add your own sources, pass the result's `directives` (nonce included) through `mergeCspDirectives` and build the header from the merged map. `nuxtPolicy` has no options for individual services beyond the ones above.
95
+
96
+ ```ts
97
+ import {
98
+ buildContentSecurityPolicy,
99
+ mergeCspDirectives,
100
+ nuxtPolicy,
101
+ } from "@neon-pixels/security";
102
+
103
+ const { directives } = nuxtPolicy({ nonce });
104
+ const policy = buildContentSecurityPolicy(
105
+ mergeCspDirectives(directives, {
106
+ "img-src": ["https://images.example.com"],
107
+ "connect-src": ["https://api.example.com"],
108
+ }),
109
+ );
110
+ ```
111
+
112
+ The nonce helpers run in a server runtime and in an edge runtime. They import no Nuxt, Nitro, h3, or Node built-in:
113
+
114
+ - `nonceForContext(context)` returns the nonce stored on a request context object (such as `event.context`), creating and storing one on first call. The server render and the response header therefore use the same value.
115
+ - `addNonceToScripts(html, nonce)` sets `nonce` on every `<script>` opening tag in an HTML chunk, replacing any existing `nonce` attribute and leaving other attributes as they were. Text that only looks like a tag inside a script body, a comment, or an attribute value is left alone.
116
+ - `addNonceToScriptTags(tags, nonce)` sets the nonce on every script entry in a list of resolved head tags (the shape unhead passes to `tags:resolve`), in every position.
117
+
118
+ Two plugins connect them to Nuxt. A Nitro plugin, `server/plugins/csp.ts`:
119
+
120
+ ```ts
121
+ import type { H3Event } from "h3";
122
+ import {
123
+ addNonceToScripts,
124
+ nonceForContext,
125
+ nuxtPolicy,
126
+ } from "@neon-pixels/security";
127
+
128
+ const SCRIPT_SECTIONS = ["head", "bodyAppend"] as const;
129
+
130
+ function sendPolicy(event: H3Event, nonce?: string) {
131
+ const { headers } = nuxtPolicy({
132
+ clerkPublishableKey: useRuntimeConfig(event).public.clerkPublishableKey,
133
+ nonce,
134
+ development: import.meta.dev,
135
+ });
136
+ for (const [name, value] of Object.entries(headers)) {
137
+ setResponseHeader(event, name, value);
138
+ }
139
+ }
140
+
141
+ export default defineNitroPlugin((nitroApp) => {
142
+ nitroApp.hooks.hook("render:html", (html, { event }) => {
143
+ const nonce = nonceForContext(event.context);
144
+ sendPolicy(event, nonce);
145
+ // Only the sections that hold nothing but unhead's own tags. "body" and
146
+ // "bodyPrepend" can carry app markup (v-html, teleports) and must never
147
+ // receive a trusted nonce.
148
+ for (const section of SCRIPT_SECTIONS) {
149
+ html[section] = html[section].map((chunk) =>
150
+ addNonceToScripts(chunk, nonce),
151
+ );
152
+ }
153
+ });
154
+ nitroApp.hooks.hook("beforeResponse", (event) => {
155
+ if (getResponseHeader(event, "Content-Security-Policy")) {
156
+ return;
157
+ }
158
+ sendPolicy(event);
159
+ });
160
+ });
161
+ ```
162
+
163
+ And a server-only Nuxt plugin, `app/plugins/cspNonce.server.ts`, that stamps the head script tags unhead resolves, including `bodyOpen` scripts the Nitro plugin does not touch:
164
+
165
+ ```ts
166
+ import {
167
+ addNonceToScriptTags,
168
+ nonceForContext,
169
+ type ResolvedHeadTag,
170
+ } from "@neon-pixels/security";
171
+
172
+ export default defineNuxtPlugin((nuxtApp) => {
173
+ const event = useRequestEvent();
174
+ const head = nuxtApp.ssrContext?.head;
175
+ if (!event || !head?.hooks) {
176
+ return;
177
+ }
178
+ const nonce = nonceForContext(event.context);
179
+ head.hooks.hook("tags:resolve", (context) => {
180
+ addNonceToScriptTags(context.tags as ResolvedHeadTag[], nonce);
181
+ });
182
+ });
183
+ ```
184
+
185
+ Scripts that unhead adds in the browser after a client-side navigation get no nonce, so register inline head scripts during the server render, and merge the hosts of any external script into `script-src`. If you add a `script-src-elem` directive of your own, add the nonce to it too, because it takes precedence over `script-src` for `<script>` elements.
186
+
187
+ A nonce only works when every HTML response is rendered per request. With `prerender`, or with `swr`, `isr`, or `cache` route rules, the HTML and its header are reused, so a nonce is either shared between visitors or missing from the page; keep those routes on `nuxtReportOnlyPolicy` or serve them a hash-based policy.
188
+
189
+ Anything passed to a `useHead` script, especially `innerHTML`, must be developer-controlled, never user input.
190
+
75
191
  ### Static sites on Netlify: `@neon-pixels/security/netlify`
76
192
 
77
193
  ```ts
@@ -85,7 +201,7 @@ await writeHeadersFile("dist", {
85
201
 
86
202
  Run it after the site is built. It reads every `.html` file under the output directory, hashes each inline `<script>` and `<style>` element (SHA-256), and writes Netlify's `_headers` file for `/*` with the security headers and a policy that carries those hashes and no `'unsafe-inline'` in `script-src` or `style-src`. The built-in policy is first-party only (`default-src 'self'`, `object-src 'none'`, `frame-ancestors 'none'`); `directives` adds sources to it.
87
203
 
88
- Options: `directives`, `reportEndpoint`, `production` (default `true`), `hstsPreload`, `extraDeniedFeatures`, and `append`. It returns `{ path, scriptHashes, styleHashes }`.
204
+ Options: `directives`, `reportEndpoint`, `reportOnly`, `production` (default `true`), `hstsPreload`, `extraDeniedFeatures`, and `append`. It returns `{ path, scriptHashes, styleHashes, unhashable }`; `unhashable` is always empty unless `reportOnly` is set.
89
205
 
90
206
  It throws `HeadersFileError` (check `error.code` and `error.files`) when:
91
207
 
@@ -94,6 +210,27 @@ It throws `HeadersFileError` (check `error.code` and `error.files`) when:
94
210
  - `headers-file-exists`: a `_headers` file is already there. Pass `append: true` to add to it.
95
211
  - `header-already-present`: with `append`, the existing file already sets one of the headers being written (`Content-Security-Policy` for example). Two values would both apply.
96
212
  - `unsafe-inline-directive`: `directives` allows `'unsafe-inline'` for scripts or styles.
213
+ - `report-endpoint-required`: `reportOnly` is set without `reportEndpoint`. A report-only policy that reports nowhere does nothing.
214
+ - `invalid-report-endpoint`: with `reportOnly`, `reportEndpoint` is not a same-origin path (`/csp-report`) or an absolute `https` URL, or it contains spaces, commas, semicolons, double quotes, backslashes, non-ASCII characters, or credentials.
215
+
216
+ #### Rolling out a hashed policy with `reportOnly`
217
+
218
+ ```ts
219
+ await writeHeadersFile("dist", {
220
+ reportOnly: true,
221
+ append: true,
222
+ reportEndpoint:
223
+ "https://o123.ingest.us.sentry.io/api/456/security/?sentry_key=abc",
224
+ });
225
+ ```
226
+
227
+ `reportOnly: true` writes the same policy under `Content-Security-Policy-Report-Only` and writes no `Content-Security-Policy`. It also leaves out `X-Content-Type-Options` and the other security headers, so the file can be appended (`append: true`) next to a site's existing headers without setting any header twice. `production`, `hstsPreload`, and `extraDeniedFeatures` have no effect in this mode, because no security headers are written. The policy string is identical to the enforced one for the same input. Inline `style` attributes, event handlers, and `javascript:` URLs do not throw in this mode; they come back as `unhashable: [{ file, attributes }]` so the build can print them.
228
+
229
+ 1. Publish report-only next to the existing policy.
230
+ 2. Fix what the reports show and what `unhashable` lists.
231
+ 3. In one change, drop `reportOnly` and remove the old `Content-Security-Policy`, `Reporting-Endpoints`, and security headers from the existing headers, because enforced mode writes them again and `append` refuses duplicates. Enforced mode also throws on unhashable markup again.
232
+
233
+ A cross-origin `reportEndpoint` (a hosted collector) receives every report unfiltered, including the blocked and document URLs. Reports are only as private as the collector. With `append`, the `Reporting-Endpoints` header this writes must not already be set in the existing file, or `header-already-present` is thrown.
97
234
 
98
235
  ### CSP reports
99
236
 
@@ -15,7 +15,7 @@ interface BuildContentSecurityPolicyOptions {
15
15
  /** Added to `script-src` as a nonce source. */
16
16
  nonce?: string;
17
17
  }
18
- /** Returns a fresh nonce: 16 random bytes, base64 encoded. */
18
+ /** Returns a fresh nonce: 16 random bytes, base64 encoded. Uses Web Crypto, so it also runs in edge runtimes. */
19
19
  declare function generateCspNonce(): string;
20
20
  /** Merges directive maps left to right, de-duplicating the sources of each directive. */
21
21
  declare function mergeCspDirectives(...maps: readonly CspDirectives[]): CspDirectives;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as generateCspNonce, c as securityHeaders, i as buildContentSecurityPolicy, n as CspDirectiveName, o as mergeCspDirectives, r as CspDirectives, s as SecurityHeadersOptions, t as BuildContentSecurityPolicyOptions } from "./csp-Cpp1B3L9.js";
1
+ import { a as generateCspNonce, c as securityHeaders, i as buildContentSecurityPolicy, n as CspDirectiveName, o as mergeCspDirectives, r as CspDirectives, s as SecurityHeadersOptions, t as BuildContentSecurityPolicyOptions } from "./csp-ByJo0mVU.js";
2
2
  /**
3
3
  * Derives the Clerk Frontend API origin from a publishable key (`pk_<env>_` plus
4
4
  * the base64 of the host and a trailing `$`). Returns undefined for a missing
@@ -23,6 +23,30 @@ interface PolicyWithReporting {
23
23
  }
24
24
  /** Adds `report-uri` and `report-to` to a policy and returns the matching `Reporting-Endpoints` value. */
25
25
  export declare function withReporting(policy: string, options: ReportingOptions): PolicyWithReporting;
26
+ /**
27
+ * Sets `nonce` on every `<script>` opening tag in an HTML chunk, replacing any
28
+ * existing `nonce` attribute and leaving other attributes as they were. Text
29
+ * inside script bodies, comments, and attribute values is never treated as a tag.
30
+ * Throws a `TypeError` for a nonce that is not base64.
31
+ */
32
+ export declare function addNonceToScripts(html: string, nonce: string): string;
33
+ interface ResolvedHeadTag {
34
+ tag: string;
35
+ tagPosition?: string;
36
+ props: Record<string, unknown>;
37
+ }
38
+ /**
39
+ * Sets the nonce on every script entry in a list of resolved head tags (the
40
+ * shape unhead passes to `tags:resolve`), whatever its position. Mutates the
41
+ * list. Anything passed to a head script must be developer-controlled.
42
+ */
43
+ export declare function addNonceToScriptTags(tags: ResolvedHeadTag[], nonce: string): void;
44
+ /**
45
+ * Returns the nonce stored on a request context object (such as `event.context`),
46
+ * creating and storing one on first call, so the server render and the response
47
+ * header use the same value.
48
+ */
49
+ export declare function nonceForContext(context: Record<string, unknown>): string;
26
50
  interface NuxtReportOnlyPolicyOptions {
27
51
  clerkPublishableKey?: string;
28
52
  sentryDsn?: string;
@@ -31,6 +55,19 @@ interface NuxtReportOnlyPolicyOptions {
31
55
  /** Where violation reports are sent. Adds `report-uri`, `report-to`, and a `Reporting-Endpoints` header. */
32
56
  reportEndpoint?: string;
33
57
  }
58
+ interface NuxtPolicyOptions extends NuxtReportOnlyPolicyOptions {
59
+ /** A fresh base64 nonce for this response (see `generateCspNonce`). Without one, no inline script is allowed. */
60
+ nonce?: string;
61
+ /** Also allow what the Nuxt development server needs: `'unsafe-eval'` scripts, `ws:`/`wss:` connections, and `'self'` frames. */
62
+ development?: boolean;
63
+ }
64
+ interface NuxtPolicy {
65
+ policy: string;
66
+ /** The directives behind `policy`, nonce included. Pass them through `mergeCspDirectives` to add your own sources. */
67
+ directives: CspDirectives;
68
+ /** Ready to send: `Content-Security-Policy`, plus `Reporting-Endpoints` when an endpoint was given. */
69
+ headers: Record<string, string>;
70
+ }
34
71
  interface NuxtReportOnlyPolicy {
35
72
  policy: string;
36
73
  /** Ready to send: `Content-Security-Policy-Report-Only`, plus `Reporting-Endpoints` when an endpoint was given. */
@@ -41,6 +78,13 @@ interface NuxtReportOnlyPolicy {
41
78
  * Whether to enforce it is the app's choice.
42
79
  */
43
80
  export declare function nuxtReportOnlyPolicy(options?: NuxtReportOnlyPolicyOptions): NuxtReportOnlyPolicy;
81
+ /**
82
+ * An enforced policy for a Nuxt app using Clerk, Sentry, and Google Analytics.
83
+ * Inline scripts need the response's nonce (no `'unsafe-inline'`); without a
84
+ * `nonce` none is allowed, which is the policy for responses that are not
85
+ * rendered pages. Throws a `TypeError` for a nonce that is not base64.
86
+ */
87
+ export declare function nuxtPolicy(options?: NuxtPolicyOptions): NuxtPolicy;
44
88
  export declare const MAX_CSP_VIOLATIONS = 20;
45
89
  export declare const MAX_CSP_FIELD_LENGTH = 512;
46
90
  interface CspViolation {
@@ -84,4 +128,4 @@ export declare class PayloadTooLargeError extends Error {
84
128
  export declare function assertContentLengthWithinLimit(header: string | null | undefined, maxBytes: number): void;
85
129
  /** Throws a 413 error when a body is larger than `maxBytes` (measured in bytes, not characters). */
86
130
  export declare function assertBodyWithinLimit(body: string | Uint8Array | ArrayBuffer, maxBytes: number): void;
87
- export { type BuildContentSecurityPolicyOptions, type CspDirectiveName, type CspDirectives, type CspReportFailureReason, type CspViolation, type NuxtReportOnlyPolicy, type NuxtReportOnlyPolicyOptions, type ParseCspReportsInput, type ParseCspReportsResult, type PolicyWithReporting, type ReportingOptions, type SecurityHeadersOptions, buildContentSecurityPolicy, generateCspNonce, mergeCspDirectives, securityHeaders };
131
+ export { type BuildContentSecurityPolicyOptions, type CspDirectiveName, type CspDirectives, type CspReportFailureReason, type CspViolation, type NuxtPolicy, type NuxtPolicyOptions, type NuxtReportOnlyPolicy, type NuxtReportOnlyPolicyOptions, type ParseCspReportsInput, type ParseCspReportsResult, type PolicyWithReporting, type ReportingOptions, type ResolvedHeadTag, type SecurityHeadersOptions, buildContentSecurityPolicy, generateCspNonce, mergeCspDirectives, securityHeaders };
package/dist/index.js CHANGED
@@ -1,7 +1,15 @@
1
- import { a as UNSAFE_INLINE_SOURCE, c as mergeCspDirectives, i as SELF_SOURCE, l as securityHeaders, n as withReporting, o as buildContentSecurityPolicy, r as NONE_SOURCE, s as generateCspNonce, t as REPORTING_ENDPOINTS_HEADER } from "./reporting-BhHtT89u.js";
1
+ import { a as SELF_SOURCE, c as assertValidCspNonce, d as isValidCspNonce, f as mergeCspDirectives, i as NONE_SOURCE, l as buildContentSecurityPolicy, n as REPORTING_ENDPOINTS_HEADER, o as UNSAFE_INLINE_SOURCE, p as securityHeaders, r as withReporting, s as addNonce, u as generateCspNonce } from "./reporting-zkOkFDrm.js";
2
2
  // src/origins.ts
3
3
  const HOSTNAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i;
4
4
  const PUBLISHABLE_KEY_PATTERN = /^pk_(?:test|live)_([A-Za-z0-9+/_-]+={0,2})$/;
5
+ function decodeBase64(encoded) {
6
+ try {
7
+ const binary = atob(encoded.replace(/-/g, "+").replace(/_/g, "/"));
8
+ return new TextDecoder().decode(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
9
+ } catch {
10
+ return;
11
+ }
12
+ }
5
13
  /**
6
14
  * Derives the Clerk Frontend API origin from a publishable key (`pk_<env>_` plus
7
15
  * the base64 of the host and a trailing `$`). Returns undefined for a missing
@@ -10,8 +18,8 @@ const PUBLISHABLE_KEY_PATTERN = /^pk_(?:test|live)_([A-Za-z0-9+/_-]+={0,2})$/;
10
18
  function clerkOriginFromPublishableKey(publishableKey) {
11
19
  const encoded = PUBLISHABLE_KEY_PATTERN.exec(publishableKey ?? "")?.[1];
12
20
  if (!encoded) return;
13
- const decoded = Buffer.from(encoded, "base64").toString("utf8");
14
- if (!decoded.endsWith("$")) return;
21
+ const decoded = decodeBase64(encoded);
22
+ if (!decoded?.endsWith("$")) return;
15
23
  const host = decoded.slice(0, -1);
16
24
  return HOSTNAME_PATTERN.test(host) ? `https://${host}` : void 0;
17
25
  }
@@ -28,12 +36,128 @@ function sentryOriginFromDsn(dsn) {
28
36
  return;
29
37
  }
30
38
  }
39
+ // src/nonce.ts
40
+ const CONTEXT_KEY = "cspNonce";
41
+ const ATTRIBUTE_PATTERN = /\s+([^\s=>]+)(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?/g;
42
+ const TAG_NAME_PATTERN = /^<([a-z][^\s/>]*)/i;
43
+ const SCRIPT_TAG_NAME = "script";
44
+ const RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set([
45
+ SCRIPT_TAG_NAME,
46
+ "style",
47
+ "textarea",
48
+ "title"
49
+ ]);
50
+ const TAG_NAME_LOOKAHEAD = 64;
51
+ const COMMENT_START = "<!--";
52
+ const COMMENT_END = "-->";
53
+ function findTagEnd(html, start) {
54
+ let quote = "";
55
+ let previous = "";
56
+ for (let index = start; index < html.length; index += 1) {
57
+ const character = html[index] ?? "";
58
+ const closesQuote = quote !== "" && character === quote;
59
+ const opensQuote = quote === "" && previous === "=" && (character === "\"" || character === "'");
60
+ if (character === ">" && quote === "") return index;
61
+ if (closesQuote) quote = "";
62
+ else if (opensQuote) quote = character;
63
+ previous = /\s/.test(character) ? previous : character;
64
+ }
65
+ return -1;
66
+ }
67
+ function findClosingTag(html, tagName, from) {
68
+ const closing = new RegExp(`</${tagName}(?=[\\s/>])`, "gi");
69
+ closing.lastIndex = from;
70
+ const match = closing.exec(html);
71
+ return match ? match.index : -1;
72
+ }
73
+ function withNonceAttribute(tag, nonce) {
74
+ const attributes = tag.slice(`<${SCRIPT_TAG_NAME}`.length, -1).replace(ATTRIBUTE_PATTERN, (attribute, name) => name.toLowerCase() === "nonce" ? "" : attribute);
75
+ return `<${SCRIPT_TAG_NAME} nonce="${nonce}"${attributes}>`;
76
+ }
77
+ /**
78
+ * Sets `nonce` on every `<script>` opening tag in an HTML chunk, replacing any
79
+ * existing `nonce` attribute and leaving other attributes as they were. Text
80
+ * inside script bodies, comments, and attribute values is never treated as a tag.
81
+ * Throws a `TypeError` for a nonce that is not base64.
82
+ */
83
+ function addNonceToScripts(html, nonce) {
84
+ assertValidCspNonce(nonce);
85
+ let output = "";
86
+ let position = 0;
87
+ while (position < html.length) {
88
+ const tagStart = html.indexOf("<", position);
89
+ if (tagStart === -1) break;
90
+ const step = readMarkup(html, tagStart, nonce);
91
+ output += html.slice(position, tagStart) + step.text;
92
+ position = step.next;
93
+ }
94
+ return output + html.slice(position);
95
+ }
96
+ function readMarkup(html, start, nonce) {
97
+ if (html.startsWith(COMMENT_START, start)) {
98
+ const end = html.indexOf(COMMENT_END, start + 4);
99
+ const next = end === -1 ? html.length : end + 3;
100
+ return {
101
+ text: html.slice(start, next),
102
+ next
103
+ };
104
+ }
105
+ const tagName = TAG_NAME_PATTERN.exec(html.slice(start, start + TAG_NAME_LOOKAHEAD))?.[1];
106
+ if (!tagName) return {
107
+ text: "<",
108
+ next: start + 1
109
+ };
110
+ const tagEnd = findTagEnd(html, start + 1);
111
+ if (tagEnd === -1) return {
112
+ text: html.slice(start),
113
+ next: html.length
114
+ };
115
+ const lowerName = tagName.toLowerCase();
116
+ const rawTag = html.slice(start, tagEnd + 1);
117
+ const tag = lowerName === SCRIPT_TAG_NAME ? withNonceAttribute(rawTag, nonce) : rawTag;
118
+ if (!RAW_TEXT_ELEMENTS.has(lowerName)) return {
119
+ text: tag,
120
+ next: tagEnd + 1
121
+ };
122
+ const closing = findClosingTag(html, lowerName, tagEnd + 1);
123
+ const next = closing === -1 ? html.length : closing;
124
+ return {
125
+ text: tag + html.slice(tagEnd + 1, next),
126
+ next
127
+ };
128
+ }
129
+ /**
130
+ * Sets the nonce on every script entry in a list of resolved head tags (the
131
+ * shape unhead passes to `tags:resolve`), whatever its position. Mutates the
132
+ * list. Anything passed to a head script must be developer-controlled.
133
+ */
134
+ function addNonceToScriptTags(tags, nonce) {
135
+ assertValidCspNonce(nonce);
136
+ for (const entry of tags) {
137
+ if (entry.tag !== SCRIPT_TAG_NAME) continue;
138
+ entry.props.nonce = nonce;
139
+ }
140
+ }
141
+ /**
142
+ * Returns the nonce stored on a request context object (such as `event.context`),
143
+ * creating and storing one on first call, so the server render and the response
144
+ * header use the same value.
145
+ */
146
+ function nonceForContext(context) {
147
+ const existing = context[CONTEXT_KEY];
148
+ if (typeof existing === "string" && isValidCspNonce(existing)) return existing;
149
+ const nonce = generateCspNonce();
150
+ context[CONTEXT_KEY] = nonce;
151
+ return nonce;
152
+ }
31
153
  // src/nuxt.ts
154
+ const ENFORCED_HEADER = "Content-Security-Policy";
32
155
  const REPORT_ONLY_HEADER = "Content-Security-Policy-Report-Only";
33
156
  const CLERK_TELEMETRY_ORIGIN = "https://clerk-telemetry.com";
34
157
  const CLERK_IMAGE_ORIGIN = "https://img.clerk.com";
35
158
  const CLERK_BOT_PROTECTION_ORIGINS = ["https://cdn.protect.clerk.com", "https://*.client.protect.clerk.com"];
36
159
  const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
160
+ const UNSAFE_EVAL_SOURCE = "'unsafe-eval'";
37
161
  const GOOGLE_TAG_MANAGER_ORIGIN = "https://www.googletagmanager.com";
38
162
  const GOOGLE_ANALYTICS_ORIGINS = [
39
163
  "https://www.google-analytics.com",
@@ -43,10 +167,20 @@ const GOOGLE_ANALYTICS_ORIGINS = [
43
167
  function present(sources) {
44
168
  return sources.filter((source) => Boolean(source));
45
169
  }
46
- function nuxtDirectives(options) {
170
+ function sharedSources(options) {
47
171
  const clerkOrigin = clerkOriginFromPublishableKey(options.clerkPublishableKey);
48
172
  const sentryOrigin = sentryOriginFromDsn(options.sentryDsn);
49
173
  const analytics = options.analytics ?? false;
174
+ return {
175
+ clerk: present([clerkOrigin]),
176
+ sentry: present([sentryOrigin]),
177
+ analyticsScripts: analytics ? [GOOGLE_TAG_MANAGER_ORIGIN] : [],
178
+ analyticsImages: analytics ? GOOGLE_ANALYTICS_ORIGINS : [],
179
+ analyticsConnections: analytics ? [GOOGLE_TAG_MANAGER_ORIGIN, ...GOOGLE_ANALYTICS_ORIGINS] : []
180
+ };
181
+ }
182
+ function nuxtDirectives(options) {
183
+ const shared = sharedSources(options);
50
184
  return {
51
185
  "default-src": [SELF_SOURCE],
52
186
  "base-uri": [SELF_SOURCE],
@@ -57,10 +191,10 @@ function nuxtDirectives(options) {
57
191
  SELF_SOURCE,
58
192
  UNSAFE_INLINE_SOURCE,
59
193
  "blob:",
60
- ...present([clerkOrigin]),
194
+ ...shared.clerk,
61
195
  ...CLERK_BOT_PROTECTION_ORIGINS,
62
196
  TURNSTILE_ORIGIN,
63
- ...analytics ? [GOOGLE_TAG_MANAGER_ORIGIN] : []
197
+ ...shared.analyticsScripts
64
198
  ],
65
199
  "style-src": [SELF_SOURCE, UNSAFE_INLINE_SOURCE],
66
200
  "img-src": [
@@ -68,40 +202,97 @@ function nuxtDirectives(options) {
68
202
  "data:",
69
203
  "blob:",
70
204
  CLERK_IMAGE_ORIGIN,
71
- ...analytics ? GOOGLE_ANALYTICS_ORIGINS : []
205
+ ...shared.analyticsImages
72
206
  ],
73
207
  "font-src": [SELF_SOURCE, "data:"],
74
208
  "connect-src": [
75
209
  SELF_SOURCE,
76
- ...present([clerkOrigin, sentryOrigin]),
210
+ ...shared.clerk,
211
+ ...shared.sentry,
77
212
  CLERK_TELEMETRY_ORIGIN,
78
213
  ...CLERK_BOT_PROTECTION_ORIGINS,
79
- ...analytics ? [GOOGLE_TAG_MANAGER_ORIGIN, ...GOOGLE_ANALYTICS_ORIGINS] : []
214
+ ...shared.analyticsConnections
80
215
  ],
81
216
  "worker-src": [SELF_SOURCE, "blob:"],
82
217
  "frame-src": [SELF_SOURCE, TURNSTILE_ORIGIN],
83
218
  "manifest-src": [SELF_SOURCE]
84
219
  };
85
220
  }
86
- /**
87
- * A report-only policy for a Nuxt app using Clerk, Sentry, and Google Analytics.
88
- * Whether to enforce it is the app's choice.
89
- */
90
- function nuxtReportOnlyPolicy(options = {}) {
91
- const policy = buildContentSecurityPolicy(nuxtDirectives(options));
92
- if (!options.reportEndpoint) return {
221
+ function devOnly(development, sources) {
222
+ return development ? sources : [];
223
+ }
224
+ function enforcedDirectives(options) {
225
+ const shared = sharedSources(options);
226
+ const development = options.development ?? false;
227
+ return {
228
+ "default-src": [SELF_SOURCE],
229
+ "base-uri": [SELF_SOURCE],
230
+ "object-src": [NONE_SOURCE],
231
+ "frame-ancestors": [NONE_SOURCE],
232
+ "form-action": [SELF_SOURCE],
233
+ "script-src": [
234
+ SELF_SOURCE,
235
+ ...devOnly(development, [UNSAFE_EVAL_SOURCE]),
236
+ ...shared.clerk,
237
+ TURNSTILE_ORIGIN,
238
+ ...shared.analyticsScripts
239
+ ],
240
+ "style-src": [SELF_SOURCE, UNSAFE_INLINE_SOURCE],
241
+ "img-src": [
242
+ SELF_SOURCE,
243
+ "data:",
244
+ "blob:",
245
+ CLERK_IMAGE_ORIGIN,
246
+ ...shared.analyticsImages
247
+ ],
248
+ "font-src": [SELF_SOURCE, "data:"],
249
+ "connect-src": [
250
+ SELF_SOURCE,
251
+ ...shared.clerk,
252
+ CLERK_TELEMETRY_ORIGIN,
253
+ ...shared.sentry,
254
+ ...shared.analyticsConnections,
255
+ ...devOnly(development, ["ws:", "wss:"])
256
+ ],
257
+ "worker-src": [SELF_SOURCE, "blob:"],
258
+ "frame-src": [...devOnly(development, [SELF_SOURCE]), TURNSTILE_ORIGIN]
259
+ };
260
+ }
261
+ function withHeaders(policy, headerName, reportEndpoint) {
262
+ if (!reportEndpoint) return {
93
263
  policy,
94
- headers: { [REPORT_ONLY_HEADER]: policy }
264
+ headers: { [headerName]: policy }
95
265
  };
96
- const reporting = withReporting(policy, { endpoint: options.reportEndpoint });
266
+ const reporting = withReporting(policy, { endpoint: reportEndpoint });
97
267
  return {
98
268
  policy: reporting.policy,
99
269
  headers: {
100
- [REPORT_ONLY_HEADER]: reporting.policy,
270
+ [headerName]: reporting.policy,
101
271
  [REPORTING_ENDPOINTS_HEADER]: reporting.reportingEndpoints
102
272
  }
103
273
  };
104
274
  }
275
+ /**
276
+ * A report-only policy for a Nuxt app using Clerk, Sentry, and Google Analytics.
277
+ * Whether to enforce it is the app's choice.
278
+ */
279
+ function nuxtReportOnlyPolicy(options = {}) {
280
+ return withHeaders(buildContentSecurityPolicy(nuxtDirectives(options)), REPORT_ONLY_HEADER, options.reportEndpoint);
281
+ }
282
+ /**
283
+ * An enforced policy for a Nuxt app using Clerk, Sentry, and Google Analytics.
284
+ * Inline scripts need the response's nonce (no `'unsafe-inline'`); without a
285
+ * `nonce` none is allowed, which is the policy for responses that are not
286
+ * rendered pages. Throws a `TypeError` for a nonce that is not base64.
287
+ */
288
+ function nuxtPolicy(options = {}) {
289
+ const base = enforcedDirectives(options);
290
+ const directives = options.nonce === void 0 ? base : addNonce(base, options.nonce);
291
+ return {
292
+ directives,
293
+ ...withHeaders(buildContentSecurityPolicy(directives), ENFORCED_HEADER, options.reportEndpoint)
294
+ };
295
+ }
105
296
  // src/reports.ts
106
297
  const MAX_CSP_VIOLATIONS = 20;
107
298
  const MAX_CSP_FIELD_LENGTH = 512;
@@ -247,4 +438,4 @@ function assertBodyWithinLimit(body, maxBytes) {
247
438
  assertValidLimit(maxBytes);
248
439
  if ((typeof body === "string" ? Buffer.byteLength(body) : body.byteLength) > maxBytes) throw new PayloadTooLargeError(maxBytes);
249
440
  }
250
- export { MAX_CSP_FIELD_LENGTH, MAX_CSP_VIOLATIONS, PayloadTooLargeError, assertBodyWithinLimit, assertContentLengthWithinLimit, buildContentSecurityPolicy, clerkOriginFromPublishableKey, generateCspNonce, mergeCspDirectives, nuxtReportOnlyPolicy, parseCspReports, securityHeaders, sentryOriginFromDsn, withReporting };
441
+ export { MAX_CSP_FIELD_LENGTH, MAX_CSP_VIOLATIONS, PayloadTooLargeError, addNonceToScriptTags, addNonceToScripts, assertBodyWithinLimit, assertContentLengthWithinLimit, buildContentSecurityPolicy, clerkOriginFromPublishableKey, generateCspNonce, mergeCspDirectives, nonceForContext, nuxtPolicy, nuxtReportOnlyPolicy, parseCspReports, securityHeaders, sentryOriginFromDsn, withReporting };
package/dist/netlify.d.ts CHANGED
@@ -1,20 +1,39 @@
1
- import { r as CspDirectives, s as SecurityHeadersOptions } from "./csp-Cpp1B3L9.js";
1
+ import { r as CspDirectives, s as SecurityHeadersOptions } from "./csp-ByJo0mVU.js";
2
2
  export interface WriteHeadersFileOptions extends Omit<SecurityHeadersOptions, "production"> {
3
3
  /** Sources added to the built-in first-party policy. Must not allow `'unsafe-inline'` for scripts or styles. */
4
4
  directives?: CspDirectives;
5
- /** Where violation reports are sent. Adds `report-uri`, `report-to`, and `Reporting-Endpoints`. */
5
+ /**
6
+ * Where violation reports are sent. Adds `report-uri`, `report-to`, and `Reporting-Endpoints`.
7
+ * With `reportOnly`, must be a same-origin path (`/csp-report`) or an absolute `https` URL;
8
+ * a collector on another origin receives every report unfiltered.
9
+ */
6
10
  reportEndpoint?: string;
11
+ /**
12
+ * Write the policy as `Content-Security-Policy-Report-Only` and skip the other security
13
+ * headers, so the file can sit next to an enforced policy with `append`. Requires
14
+ * `reportEndpoint`. Inline style attributes, event handlers, and `javascript:` URLs are
15
+ * listed in the result's `unhashable` instead of throwing.
16
+ */
17
+ reportOnly?: boolean;
7
18
  /** Add to an existing `_headers` file instead of refusing to overwrite it. */
8
19
  append?: boolean;
9
20
  /** Include the production-only headers (HSTS, X-Frame-Options). Defaults to true: the file is for a deployed build. */
10
21
  production?: boolean;
11
22
  }
23
+ /** A page's inline markup that no hash can cover, such as `<p style>` or `<button onclick>`. */
24
+ export interface UnhashableFile {
25
+ /** Path relative to the output directory. */
26
+ file: string;
27
+ attributes: string[];
28
+ }
12
29
  export interface WriteHeadersFileResult {
13
30
  path: string;
14
31
  scriptHashes: string[];
15
32
  styleHashes: string[];
33
+ /** What must be fixed before enforcing. Always empty when enforcing, because that throws instead. */
34
+ unhashable: UnhashableFile[];
16
35
  }
17
- export type HeadersFileErrorCode = "no-html" | "unhashable-inline" | "headers-file-exists" | "header-already-present" | "unsafe-inline-directive";
36
+ export type HeadersFileErrorCode = "no-html" | "unhashable-inline" | "headers-file-exists" | "header-already-present" | "unsafe-inline-directive" | "report-endpoint-required" | "invalid-report-endpoint";
18
37
  /** Thrown for every way writeHeadersFile refuses to write. `files` lists the offending paths. */
19
38
  export declare class HeadersFileError extends Error {
20
39
  name: string;
@@ -27,6 +46,8 @@ export declare class HeadersFileError extends Error {
27
46
  * `<script>` and `<style>` element is hashed (SHA-256), so the policy needs no
28
47
  * `'unsafe-inline'`. Fails, naming the files, when the site has inline style
29
48
  * attributes or event handlers; fails when there is no HTML; refuses to
30
- * overwrite an existing `_headers` file unless `append` is set.
49
+ * overwrite an existing `_headers` file unless `append` is set. With
50
+ * `reportOnly` it writes `Content-Security-Policy-Report-Only` instead and
51
+ * lists the unhashable markup in the result rather than failing.
31
52
  */
32
53
  export declare function writeHeadersFile(outDir: string, options?: WriteHeadersFileOptions): Promise<WriteHeadersFileResult>;
package/dist/netlify.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { appendFile, readFile, readdir, writeFile } from "node:fs/promises";
3
3
  import { join, relative } from "node:path";
4
- import { a as UNSAFE_INLINE_SOURCE, c as mergeCspDirectives, i as SELF_SOURCE, l as securityHeaders, n as withReporting, o as buildContentSecurityPolicy, r as NONE_SOURCE, t as REPORTING_ENDPOINTS_HEADER } from "./reporting-BhHtT89u.js";
4
+ import { a as SELF_SOURCE, f as mergeCspDirectives, i as NONE_SOURCE, l as buildContentSecurityPolicy, n as REPORTING_ENDPOINTS_HEADER, o as UNSAFE_INLINE_SOURCE, p as securityHeaders, r as withReporting, t as FORBIDDEN_ENDPOINT_PATTERN } from "./reporting-zkOkFDrm.js";
5
5
  import { createHash } from "node:crypto";
6
6
  // src/inline.ts
7
7
  const HASH_ALGORITHM = "sha256";
@@ -111,6 +111,9 @@ const HEADERS_FILENAME = "_headers";
111
111
  const HTML_EXTENSION = ".html";
112
112
  const HEADER_INDENT = " ";
113
113
  const CSP_HEADER_NAME = "Content-Security-Policy";
114
+ const CSP_REPORT_ONLY_HEADER_NAME = "Content-Security-Policy-Report-Only";
115
+ const HTTPS_PROTOCOL = "https:";
116
+ const HTTPS_PREFIX = "https://";
114
117
  const SCRIPT_HASH_DIRECTIVES = ["script-src", "script-src-elem"];
115
118
  const STYLE_HASH_DIRECTIVES = ["style-src", "style-src-elem"];
116
119
  const UNSAFE_INLINE_DIRECTIVES = [
@@ -153,6 +156,17 @@ function assertNoUnsafeInline(directives) {
153
156
  if (offending.length === 0) return;
154
157
  throw new HeadersFileError("unsafe-inline-directive", `directives must not allow 'unsafe-inline' in ${offending.join(", ")}: the hashes replace it`);
155
158
  }
159
+ function isSafeHttpsUrl(endpoint) {
160
+ const url = URL.canParse(endpoint) ? new URL(endpoint) : void 0;
161
+ return url?.protocol === HTTPS_PROTOCOL && endpoint.toLowerCase().startsWith(HTTPS_PREFIX) && !url.username && !url.password;
162
+ }
163
+ function isSameOriginPath(endpoint) {
164
+ return endpoint.startsWith("/") && !endpoint.startsWith("//");
165
+ }
166
+ function assertReportOnlyEndpoint(endpoint) {
167
+ if (!endpoint) throw new HeadersFileError("report-endpoint-required", "reportOnly needs a reportEndpoint: a report-only policy that reports nowhere does nothing");
168
+ if (!(!FORBIDDEN_ENDPOINT_PATTERN.test(endpoint) && (isSameOriginPath(endpoint) || isSafeHttpsUrl(endpoint)))) throw new HeadersFileError("invalid-report-endpoint", `reportEndpoint must be a same-origin path or an absolute https URL with no spaces, commas, semicolons, double quotes, backslashes, non-ASCII characters, or credentials: ${JSON.stringify(endpoint)}`);
169
+ }
156
170
  function formatHeadersBlock(headers) {
157
171
  return `/*\n${Object.entries(headers).map(([name, value]) => `${HEADER_INDENT}${name}: ${value}`).join("\n")}\n`;
158
172
  }
@@ -168,19 +182,20 @@ function hashDirectives(supplied, scriptHashes, styleHashes) {
168
182
  function buildHeaders(options, scriptHashes, styleHashes) {
169
183
  const directives = mergeCspDirectives(BASE_DIRECTIVES, options.directives ?? {}, hashDirectives(options.directives ?? {}, scriptHashes, styleHashes));
170
184
  const policy = buildContentSecurityPolicy(directives);
171
- const headers = securityHeaders({
185
+ const policyHeaderName = options.reportOnly ? CSP_REPORT_ONLY_HEADER_NAME : CSP_HEADER_NAME;
186
+ const headers = options.reportOnly ? {} : securityHeaders({
172
187
  production: options.production ?? true,
173
188
  hstsPreload: options.hstsPreload,
174
189
  extraDeniedFeatures: options.extraDeniedFeatures
175
190
  });
176
191
  if (!options.reportEndpoint) return {
177
192
  ...headers,
178
- [CSP_HEADER_NAME]: policy
193
+ [policyHeaderName]: policy
179
194
  };
180
195
  const reporting = withReporting(policy, { endpoint: options.reportEndpoint });
181
196
  return {
182
197
  ...headers,
183
- [CSP_HEADER_NAME]: reporting.policy,
198
+ [policyHeaderName]: reporting.policy,
184
199
  [REPORTING_ENDPOINTS_HEADER]: reporting.reportingEndpoints
185
200
  };
186
201
  }
@@ -198,26 +213,28 @@ async function persistBlock(headersPath, block, headerNames) {
198
213
  if (duplicated.length > 0) throw new HeadersFileError("header-already-present", `${HEADERS_FILENAME} already sets ${duplicated.join(", ")}; appending would send both values`, [HEADERS_FILENAME]);
199
214
  await appendFile(headersPath, `\n${block}`);
200
215
  }
216
+ function unhashableError(unhashable) {
217
+ return new HeadersFileError("unhashable-inline", `Inline style attributes, event handlers, and javascript: URLs cannot be covered by a hash. Move them out of the markup:\n${unhashable.flatMap(({ file, attributes }) => attributes.map((attribute) => `${file}: ${attribute}`)).join("\n")}`, unhashable.map(({ file }) => file));
218
+ }
201
219
  async function scanSite(outDir) {
202
220
  const htmlFiles = await findHtmlFiles(outDir);
203
221
  if (htmlFiles.length === 0) throw new HeadersFileError("no-html", `No HTML files found in ${outDir}`);
204
222
  const scriptHashes = /* @__PURE__ */ new Set();
205
223
  const styleHashes = /* @__PURE__ */ new Set();
206
- const unhashableFiles = /* @__PURE__ */ new Set();
207
- const unhashableDetails = [];
224
+ const unhashable = [];
208
225
  for (const file of htmlFiles) {
209
226
  const findings = findInlineSources(await readFile(file, "utf8"));
210
227
  findings.scriptHashes.forEach((hash) => scriptHashes.add(hash));
211
228
  findings.styleHashes.forEach((hash) => styleHashes.add(hash));
212
- const relativePath = relative(outDir, file);
213
- if (findings.unhashable.length > 0) unhashableFiles.add(relativePath);
214
- unhashableDetails.push(...findings.unhashable.map((entry) => `${relativePath}: ${entry}`));
229
+ if (findings.unhashable.length > 0) unhashable.push({
230
+ file: relative(outDir, file),
231
+ attributes: findings.unhashable
232
+ });
215
233
  }
216
234
  return {
217
235
  scriptHashes: [...scriptHashes].sort(),
218
236
  styleHashes: [...styleHashes].sort(),
219
- unhashableFiles: [...unhashableFiles],
220
- unhashableDetails
237
+ unhashable
221
238
  };
222
239
  }
223
240
  /**
@@ -225,20 +242,24 @@ async function scanSite(outDir) {
225
242
  * `<script>` and `<style>` element is hashed (SHA-256), so the policy needs no
226
243
  * `'unsafe-inline'`. Fails, naming the files, when the site has inline style
227
244
  * attributes or event handlers; fails when there is no HTML; refuses to
228
- * overwrite an existing `_headers` file unless `append` is set.
245
+ * overwrite an existing `_headers` file unless `append` is set. With
246
+ * `reportOnly` it writes `Content-Security-Policy-Report-Only` instead and
247
+ * lists the unhashable markup in the result rather than failing.
229
248
  */
230
249
  async function writeHeadersFile(outDir, options = {}) {
231
250
  assertNoUnsafeInline(options.directives ?? {});
251
+ if (options.reportOnly) assertReportOnlyEndpoint(options.reportEndpoint);
232
252
  const headersPath = join(outDir, HEADERS_FILENAME);
233
253
  if (existsSync(headersPath) && !options.append) throw new HeadersFileError("headers-file-exists", `${HEADERS_FILENAME} already exists in ${outDir}; pass append to add to it`, [HEADERS_FILENAME]);
234
254
  const site = await scanSite(outDir);
235
- if (site.unhashableFiles.length > 0) throw new HeadersFileError("unhashable-inline", `Inline style attributes, event handlers, and javascript: URLs cannot be covered by a hash. Move them out of the markup:\n${site.unhashableDetails.join("\n")}`, site.unhashableFiles);
255
+ if (site.unhashable.length > 0 && !options.reportOnly) throw unhashableError(site.unhashable);
236
256
  const headers = buildHeaders(options, site.scriptHashes, site.styleHashes);
237
257
  await persistBlock(headersPath, formatHeadersBlock(headers), Object.keys(headers));
238
258
  return {
239
259
  path: headersPath,
240
260
  scriptHashes: site.scriptHashes,
241
- styleHashes: site.styleHashes
261
+ styleHashes: site.styleHashes,
262
+ unhashable: site.unhashable
242
263
  };
243
264
  }
244
265
  export { HeadersFileError, writeHeadersFile };
@@ -1,4 +1,3 @@
1
- import { randomBytes } from "node:crypto";
2
1
  // src/headers.ts
3
2
  const BASE_DENIED_FEATURES = [
4
3
  "camera",
@@ -39,9 +38,23 @@ const UNSAFE_INLINE_SOURCE = "'unsafe-inline'";
39
38
  const SCRIPT_SRC_ELEM = "script-src-elem";
40
39
  const DIRECTIVE_NAME_PATTERN = /^[a-z][a-z-]*$/;
41
40
  const NONCE_PATTERN = /^[A-Za-z0-9+/_-]+=*$/;
42
- /** Returns a fresh nonce: 16 random bytes, base64 encoded. */
41
+ /** Returns a fresh nonce: 16 random bytes, base64 encoded. Uses Web Crypto, so it also runs in edge runtimes. */
43
42
  function generateCspNonce() {
44
- return randomBytes(NONCE_BYTE_LENGTH).toString("base64");
43
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(NONCE_BYTE_LENGTH));
44
+ return btoa(String.fromCharCode(...bytes));
45
+ }
46
+ /** Throws a `TypeError` unless the value is a base64 nonce. */
47
+ function assertValidCspNonce(nonce) {
48
+ if (!isValidCspNonce(nonce)) throw new TypeError("Invalid CSP nonce");
49
+ }
50
+ /** The `script-src` source for a nonce, such as `'nonce-abc='`. Validates the nonce. */
51
+ function nonceSource(nonce) {
52
+ assertValidCspNonce(nonce);
53
+ return `'nonce-${nonce}'`;
54
+ }
55
+ /** True when the value is base64 (standard or URL-safe alphabet), so it cannot break out of a header or an attribute. */
56
+ function isValidCspNonce(nonce) {
57
+ return typeof nonce === "string" && NONCE_PATTERN.test(nonce);
45
58
  }
46
59
  function unique(sources) {
47
60
  return [...new Set(sources)];
@@ -69,15 +82,14 @@ function serializeDirective(name, sources) {
69
82
  return [name, ...withoutRedundantNone(unique(sources))].join(" ");
70
83
  }
71
84
  function addNonce(directives, nonce) {
72
- if (!NONCE_PATTERN.test(nonce)) throw new TypeError("Invalid CSP nonce");
73
- const nonceSource = `'nonce-${nonce}'`;
85
+ const source = nonceSource(nonce);
74
86
  const inherited = directives[SCRIPT_SRC] ?? directives[DEFAULT_SRC] ?? [];
75
87
  const withNonce = {
76
88
  ...directives,
77
- [SCRIPT_SRC]: [...inherited, nonceSource]
89
+ [SCRIPT_SRC]: [...inherited, source]
78
90
  };
79
91
  const elementSources = directives[SCRIPT_SRC_ELEM];
80
- if (elementSources) withNonce[SCRIPT_SRC_ELEM] = [...elementSources, nonceSource];
92
+ if (elementSources) withNonce[SCRIPT_SRC_ELEM] = [...elementSources, source];
81
93
  return withNonce;
82
94
  }
83
95
  /** Turns a directive map into a Content-Security-Policy string. */
@@ -105,4 +117,4 @@ function withReporting(policy, options) {
105
117
  reportingEndpoints: `${group}="${options.endpoint}"`
106
118
  };
107
119
  }
108
- export { UNSAFE_INLINE_SOURCE as a, mergeCspDirectives as c, SELF_SOURCE as i, securityHeaders as l, withReporting as n, buildContentSecurityPolicy as o, NONE_SOURCE as r, generateCspNonce as s, REPORTING_ENDPOINTS_HEADER as t };
120
+ export { SELF_SOURCE as a, assertValidCspNonce as c, isValidCspNonce as d, mergeCspDirectives as f, NONE_SOURCE as i, buildContentSecurityPolicy as l, REPORTING_ENDPOINTS_HEADER as n, UNSAFE_INLINE_SOURCE as o, securityHeaders as p, withReporting as r, addNonce as s, FORBIDDEN_ENDPOINT_PATTERN as t, generateCspNonce as u };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neon-pixels/security",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Security response headers, a Content-Security-Policy builder, a hashed policy build step for static sites, and CSP report parsing.",
5
5
  "license": "MIT",
6
6
  "type": "module",