@neon-pixels/security 0.0.0-stage → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Neon Pixels Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,126 @@
1
- # Temporary Holding Version
1
+ # @neon-pixels/security
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Security response headers, a Content-Security-Policy (CSP) builder, a build step that writes a hashed policy for static sites, and a parser for CSP violation reports. No framework dependency and no runtime dependency beyond Node built-ins.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm add @neon-pixels/security
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Headers
14
+
15
+ ```ts
16
+ import { securityHeaders } from "@neon-pixels/security";
17
+
18
+ securityHeaders({
19
+ production: process.env.NODE_ENV === "production",
20
+ hstsPreload: false,
21
+ extraDeniedFeatures: ["payment"],
22
+ });
23
+ ```
24
+
25
+ Always returns `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, and a `Permissions-Policy` denying `camera`, `microphone`, `geolocation`, and any `extraDeniedFeatures`. With `production: true` it also adds `Strict-Transport-Security: max-age=63072000; includeSubDomains` (plus `preload` when `hstsPreload` is set) and `X-Frame-Options: DENY`. Leave `preload` off until you mean it: list submission is hard to undo.
26
+
27
+ ### Content-Security-Policy
28
+
29
+ ```ts
30
+ import {
31
+ buildContentSecurityPolicy,
32
+ clerkOriginFromPublishableKey,
33
+ generateCspNonce,
34
+ sentryOriginFromDsn,
35
+ withReporting,
36
+ } from "@neon-pixels/security";
37
+
38
+ const clerkOrigin = clerkOriginFromPublishableKey(key);
39
+ const sentryOrigin = sentryOriginFromDsn(dsn);
40
+ const nonce = generateCspNonce();
41
+ const policy = buildContentSecurityPolicy(
42
+ {
43
+ "default-src": ["'self'"],
44
+ "script-src": ["'self'", ...(clerkOrigin ? [clerkOrigin] : [])],
45
+ "connect-src": ["'self'", ...(sentryOrigin ? [sentryOrigin] : [])],
46
+ },
47
+ { nonce },
48
+ );
49
+ const { policy: reporting, reportingEndpoints } = withReporting(policy, {
50
+ endpoint: "/csp-report",
51
+ });
52
+ ```
53
+
54
+ - `buildContentSecurityPolicy(directives, { nonce })` joins a typed directive map into a policy string and de-duplicates sources. An empty list writes a bare directive (`upgrade-insecure-requests`). With `nonce` it adds `'nonce-...'` to `script-src` (a missing `script-src` starts from the `default-src` sources). A source containing whitespace, `;`, or `,` throws a `TypeError`, so a value cannot inject another directive.
55
+ - `mergeCspDirectives(...maps)` merges directive maps and de-duplicates.
56
+ - `generateCspNonce()` returns 16 random bytes, base64 encoded. Use a new one per response.
57
+ - `clerkOriginFromPublishableKey(key)` and `sentryOriginFromDsn(dsn)` return the origin to allow, or `undefined` for a missing or malformed value. Filter the `undefined` out before passing sources.
58
+ - `withReporting(policy, { endpoint, group })` adds `report-uri` and `report-to` (replacing any already there) and returns `{ policy, reportingEndpoints }`. Send `reportingEndpoints` as the `Reporting-Endpoints` header. `group` defaults to `csp-endpoint`.
59
+
60
+ ### Nuxt report-only preset
61
+
62
+ ```ts
63
+ import { nuxtReportOnlyPolicy } from "@neon-pixels/security";
64
+
65
+ const { headers } = nuxtReportOnlyPolicy({
66
+ clerkPublishableKey,
67
+ sentryDsn,
68
+ analytics: true,
69
+ reportEndpoint: "/csp-report",
70
+ });
71
+ ```
72
+
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
+
75
+ ### Static sites on Netlify: `@neon-pixels/security/netlify`
76
+
77
+ ```ts
78
+ import { writeHeadersFile } from "@neon-pixels/security/netlify";
79
+
80
+ await writeHeadersFile("dist", {
81
+ directives: { "img-src": ["'self'", "data:"] },
82
+ reportEndpoint: "/csp-report",
83
+ });
84
+ ```
85
+
86
+ 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
+
88
+ Options: `directives`, `reportEndpoint`, `production` (default `true`), `hstsPreload`, `extraDeniedFeatures`, and `append`. It returns `{ path, scriptHashes, styleHashes }`.
89
+
90
+ It throws `HeadersFileError` (check `error.code` and `error.files`) when:
91
+
92
+ - `unhashable-inline`: a page has an inline `style` attribute, an event handler such as `onclick`, or a `javascript:` URL. A hash cannot cover those. `error.files` lists each file once (relative to the output directory) and the message lists every offending attribute.
93
+ - `no-html`: the directory holds no HTML, which usually means the wrong directory.
94
+ - `headers-file-exists`: a `_headers` file is already there. Pass `append: true` to add to it.
95
+ - `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
+ - `unsafe-inline-directive`: `directives` allows `'unsafe-inline'` for scripts or styles.
97
+
98
+ ### CSP reports
99
+
100
+ ```ts
101
+ import {
102
+ assertBodyWithinLimit,
103
+ assertContentLengthWithinLimit,
104
+ parseCspReports,
105
+ } from "@neon-pixels/security";
106
+
107
+ const MAX_BYTES = 16 * 1024;
108
+ assertContentLengthWithinLimit(
109
+ request.headers.get("content-length"),
110
+ MAX_BYTES,
111
+ );
112
+ const body = await request.text();
113
+ assertBodyWithinLimit(body, MAX_BYTES);
114
+
115
+ const result = parseCspReports({
116
+ contentType: request.headers.get("content-type"),
117
+ body,
118
+ });
119
+ if (!result.ok) {
120
+ // result.reason: "unsupported-content-type" | "malformed-body"
121
+ }
122
+ ```
123
+
124
+ `parseCspReports` accepts `application/csp-report`, `application/reports+json`, and `application/json`. It returns `{ ok: true, violations }` with at most 20 violations, every field cut to 512 characters, and every URL stripped of its query string, fragment, and credentials. It never throws: an unknown content type or a body that is not a JSON object or array returns `{ ok: false, reason }`.
125
+
126
+ `assertContentLengthWithinLimit(header, maxBytes)` and `assertBodyWithinLimit(body, maxBytes)` throw `PayloadTooLargeError`, which carries `status` 413. A missing or non-numeric `Content-Length` passes the first check, so always run the second on the body you read. The body check runs after the body is in memory: for chunked uploads, also cap the read itself with your framework's body-size option. This package does not store, forward, or prune reports.
@@ -0,0 +1,24 @@
1
+ interface SecurityHeadersOptions {
2
+ /** Adds Strict-Transport-Security and X-Frame-Options. Off by default so local development is unaffected. */
3
+ production?: boolean;
4
+ /** Adds `preload` to Strict-Transport-Security. Only applies in production. */
5
+ hstsPreload?: boolean;
6
+ /** Features denied in Permissions-Policy in addition to camera, microphone, and geolocation. */
7
+ extraDeniedFeatures?: readonly string[];
8
+ }
9
+ /** Returns the baseline security response headers as a plain record. */
10
+ declare function securityHeaders(options?: SecurityHeadersOptions): Record<string, string>;
11
+ type CspDirectiveName = "default-src" | "script-src" | "script-src-elem" | "script-src-attr" | "style-src" | "style-src-elem" | "style-src-attr" | "img-src" | "font-src" | "connect-src" | "media-src" | "object-src" | "frame-src" | "child-src" | "worker-src" | "manifest-src" | "prefetch-src" | "base-uri" | "form-action" | "frame-ancestors" | "sandbox" | "upgrade-insecure-requests";
12
+ /** Sources per directive. An empty list writes a bare directive such as `upgrade-insecure-requests`. */
13
+ type CspDirectives = { [name in CspDirectiveName]?: readonly string[]; };
14
+ interface BuildContentSecurityPolicyOptions {
15
+ /** Added to `script-src` as a nonce source. */
16
+ nonce?: string;
17
+ }
18
+ /** Returns a fresh nonce: 16 random bytes, base64 encoded. */
19
+ declare function generateCspNonce(): string;
20
+ /** Merges directive maps left to right, de-duplicating the sources of each directive. */
21
+ declare function mergeCspDirectives(...maps: readonly CspDirectives[]): CspDirectives;
22
+ /** Turns a directive map into a Content-Security-Policy string. */
23
+ declare function buildContentSecurityPolicy(directives: CspDirectives, options?: BuildContentSecurityPolicyOptions): string;
24
+ export { generateCspNonce as a, securityHeaders as c, buildContentSecurityPolicy as i, CspDirectiveName as n, mergeCspDirectives as o, CspDirectives as r, SecurityHeadersOptions as s, BuildContentSecurityPolicyOptions as t };
@@ -0,0 +1,87 @@
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";
2
+ /**
3
+ * Derives the Clerk Frontend API origin from a publishable key (`pk_<env>_` plus
4
+ * the base64 of the host and a trailing `$`). Returns undefined for a missing
5
+ * or malformed key.
6
+ */
7
+ export declare function clerkOriginFromPublishableKey(publishableKey: string | null | undefined): string | undefined;
8
+ /**
9
+ * Derives the ingest origin from a Sentry DSN. Returns undefined for a missing
10
+ * or malformed value, or one that is not https.
11
+ */
12
+ export declare function sentryOriginFromDsn(dsn: string | null | undefined): string | undefined;
13
+ interface ReportingOptions {
14
+ /** Where reports are sent: a path such as `/csp-report` or an https URL. */
15
+ endpoint: string;
16
+ /** Names the endpoint in `report-to` and `Reporting-Endpoints`. Defaults to `csp-endpoint`. */
17
+ group?: string;
18
+ }
19
+ interface PolicyWithReporting {
20
+ policy: string;
21
+ /** Value for the `Reporting-Endpoints` response header. */
22
+ reportingEndpoints: string;
23
+ }
24
+ /** Adds `report-uri` and `report-to` to a policy and returns the matching `Reporting-Endpoints` value. */
25
+ export declare function withReporting(policy: string, options: ReportingOptions): PolicyWithReporting;
26
+ interface NuxtReportOnlyPolicyOptions {
27
+ clerkPublishableKey?: string;
28
+ sentryDsn?: string;
29
+ /** Allow Google Analytics (gtag.js and its collection endpoints). */
30
+ analytics?: boolean;
31
+ /** Where violation reports are sent. Adds `report-uri`, `report-to`, and a `Reporting-Endpoints` header. */
32
+ reportEndpoint?: string;
33
+ }
34
+ interface NuxtReportOnlyPolicy {
35
+ policy: string;
36
+ /** Ready to send: `Content-Security-Policy-Report-Only`, plus `Reporting-Endpoints` when an endpoint was given. */
37
+ headers: Record<string, string>;
38
+ }
39
+ /**
40
+ * A report-only policy for a Nuxt app using Clerk, Sentry, and Google Analytics.
41
+ * Whether to enforce it is the app's choice.
42
+ */
43
+ export declare function nuxtReportOnlyPolicy(options?: NuxtReportOnlyPolicyOptions): NuxtReportOnlyPolicy;
44
+ export declare const MAX_CSP_VIOLATIONS = 20;
45
+ export declare const MAX_CSP_FIELD_LENGTH = 512;
46
+ interface CspViolation {
47
+ documentUri: string | null;
48
+ referrer: string | null;
49
+ blockedUri: string | null;
50
+ effectiveDirective: string | null;
51
+ violatedDirective: string | null;
52
+ disposition: string | null;
53
+ sourceFile: string | null;
54
+ lineNumber: number | null;
55
+ columnNumber: number | null;
56
+ statusCode: number | null;
57
+ }
58
+ type CspReportFailureReason = "unsupported-content-type" | "malformed-body";
59
+ type ParseCspReportsResult = {
60
+ ok: true;
61
+ violations: CspViolation[];
62
+ } | {
63
+ ok: false;
64
+ reason: CspReportFailureReason;
65
+ };
66
+ interface ParseCspReportsInput {
67
+ contentType: string | null | undefined;
68
+ body: string;
69
+ }
70
+ /**
71
+ * Parses a CSP violation report request. Returns at most 20 violations with
72
+ * every field cut to 512 characters and every URL stripped of query string,
73
+ * fragment, and credentials. Never throws: failures come back as a typed result.
74
+ */
75
+ export declare function parseCspReports(input: ParseCspReportsInput): ParseCspReportsResult;
76
+ /** Thrown when a request body is over the allowed size. Carries the HTTP status to answer with. */
77
+ export declare class PayloadTooLargeError extends Error {
78
+ name: string;
79
+ readonly status = 413;
80
+ readonly maxBytes: number;
81
+ constructor(maxBytes: number);
82
+ }
83
+ /** Throws a 413 error when a Content-Length header declares more than `maxBytes`. A missing or unparseable header passes: the body check still applies. */
84
+ export declare function assertContentLengthWithinLimit(header: string | null | undefined, maxBytes: number): void;
85
+ /** Throws a 413 error when a body is larger than `maxBytes` (measured in bytes, not characters). */
86
+ 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 };
package/dist/index.js ADDED
@@ -0,0 +1,250 @@
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";
2
+ // src/origins.ts
3
+ const HOSTNAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i;
4
+ const PUBLISHABLE_KEY_PATTERN = /^pk_(?:test|live)_([A-Za-z0-9+/_-]+={0,2})$/;
5
+ /**
6
+ * Derives the Clerk Frontend API origin from a publishable key (`pk_<env>_` plus
7
+ * the base64 of the host and a trailing `$`). Returns undefined for a missing
8
+ * or malformed key.
9
+ */
10
+ function clerkOriginFromPublishableKey(publishableKey) {
11
+ const encoded = PUBLISHABLE_KEY_PATTERN.exec(publishableKey ?? "")?.[1];
12
+ if (!encoded) return;
13
+ const decoded = Buffer.from(encoded, "base64").toString("utf8");
14
+ if (!decoded.endsWith("$")) return;
15
+ const host = decoded.slice(0, -1);
16
+ return HOSTNAME_PATTERN.test(host) ? `https://${host}` : void 0;
17
+ }
18
+ /**
19
+ * Derives the ingest origin from a Sentry DSN. Returns undefined for a missing
20
+ * or malformed value, or one that is not https.
21
+ */
22
+ function sentryOriginFromDsn(dsn) {
23
+ if (!dsn) return;
24
+ try {
25
+ const url = new URL(dsn);
26
+ return url.protocol === "https:" ? url.origin : void 0;
27
+ } catch {
28
+ return;
29
+ }
30
+ }
31
+ // src/nuxt.ts
32
+ const REPORT_ONLY_HEADER = "Content-Security-Policy-Report-Only";
33
+ const CLERK_TELEMETRY_ORIGIN = "https://clerk-telemetry.com";
34
+ const CLERK_IMAGE_ORIGIN = "https://img.clerk.com";
35
+ const CLERK_BOT_PROTECTION_ORIGINS = ["https://cdn.protect.clerk.com", "https://*.client.protect.clerk.com"];
36
+ const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
37
+ const GOOGLE_TAG_MANAGER_ORIGIN = "https://www.googletagmanager.com";
38
+ const GOOGLE_ANALYTICS_ORIGINS = [
39
+ "https://www.google-analytics.com",
40
+ "https://*.google-analytics.com",
41
+ "https://*.analytics.google.com"
42
+ ];
43
+ function present(sources) {
44
+ return sources.filter((source) => Boolean(source));
45
+ }
46
+ function nuxtDirectives(options) {
47
+ const clerkOrigin = clerkOriginFromPublishableKey(options.clerkPublishableKey);
48
+ const sentryOrigin = sentryOriginFromDsn(options.sentryDsn);
49
+ const analytics = options.analytics ?? false;
50
+ return {
51
+ "default-src": [SELF_SOURCE],
52
+ "base-uri": [SELF_SOURCE],
53
+ "object-src": [NONE_SOURCE],
54
+ "frame-ancestors": [NONE_SOURCE],
55
+ "form-action": [SELF_SOURCE],
56
+ "script-src": [
57
+ SELF_SOURCE,
58
+ UNSAFE_INLINE_SOURCE,
59
+ "blob:",
60
+ ...present([clerkOrigin]),
61
+ ...CLERK_BOT_PROTECTION_ORIGINS,
62
+ TURNSTILE_ORIGIN,
63
+ ...analytics ? [GOOGLE_TAG_MANAGER_ORIGIN] : []
64
+ ],
65
+ "style-src": [SELF_SOURCE, UNSAFE_INLINE_SOURCE],
66
+ "img-src": [
67
+ SELF_SOURCE,
68
+ "data:",
69
+ "blob:",
70
+ CLERK_IMAGE_ORIGIN,
71
+ ...analytics ? GOOGLE_ANALYTICS_ORIGINS : []
72
+ ],
73
+ "font-src": [SELF_SOURCE, "data:"],
74
+ "connect-src": [
75
+ SELF_SOURCE,
76
+ ...present([clerkOrigin, sentryOrigin]),
77
+ CLERK_TELEMETRY_ORIGIN,
78
+ ...CLERK_BOT_PROTECTION_ORIGINS,
79
+ ...analytics ? [GOOGLE_TAG_MANAGER_ORIGIN, ...GOOGLE_ANALYTICS_ORIGINS] : []
80
+ ],
81
+ "worker-src": [SELF_SOURCE, "blob:"],
82
+ "frame-src": [SELF_SOURCE, TURNSTILE_ORIGIN],
83
+ "manifest-src": [SELF_SOURCE]
84
+ };
85
+ }
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 {
93
+ policy,
94
+ headers: { [REPORT_ONLY_HEADER]: policy }
95
+ };
96
+ const reporting = withReporting(policy, { endpoint: options.reportEndpoint });
97
+ return {
98
+ policy: reporting.policy,
99
+ headers: {
100
+ [REPORT_ONLY_HEADER]: reporting.policy,
101
+ [REPORTING_ENDPOINTS_HEADER]: reporting.reportingEndpoints
102
+ }
103
+ };
104
+ }
105
+ // src/reports.ts
106
+ const MAX_CSP_VIOLATIONS = 20;
107
+ const MAX_CSP_FIELD_LENGTH = 512;
108
+ const CSP_REPORT_TYPE = "csp-violation";
109
+ const ACCEPTED_CONTENT_TYPES = /* @__PURE__ */ new Set([
110
+ "application/csp-report",
111
+ "application/reports+json",
112
+ "application/json"
113
+ ]);
114
+ function isRecord(value) {
115
+ return typeof value === "object" && value !== null && !Array.isArray(value);
116
+ }
117
+ function contentTypeEssence(contentType) {
118
+ return (contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
119
+ }
120
+ function stripWithoutParsing(value) {
121
+ const withoutQuery = value.split(/[?#]/)[0] ?? "";
122
+ const authorityStart = withoutQuery.indexOf("//");
123
+ if (authorityStart === -1) return withoutQuery;
124
+ const authorityOffset = authorityStart + 2;
125
+ const pathStart = withoutQuery.indexOf("/", authorityOffset);
126
+ const authorityEnd = pathStart === -1 ? withoutQuery.length : pathStart;
127
+ const atIndex = withoutQuery.lastIndexOf("@", authorityEnd);
128
+ if (atIndex < authorityOffset) return withoutQuery;
129
+ return withoutQuery.slice(0, authorityOffset) + withoutQuery.slice(atIndex + 1);
130
+ }
131
+ function stripUrlDetails(value) {
132
+ try {
133
+ const url = new URL(value);
134
+ url.search = "";
135
+ url.hash = "";
136
+ url.username = "";
137
+ url.password = "";
138
+ return url.href;
139
+ } catch {
140
+ return stripWithoutParsing(value);
141
+ }
142
+ }
143
+ function firstValue(fields, keys) {
144
+ const key = keys.find((candidate) => fields[candidate] !== void 0);
145
+ return key === void 0 ? void 0 : fields[key];
146
+ }
147
+ function readText(fields, keys) {
148
+ const value = firstValue(fields, keys);
149
+ if (typeof value !== "string" || value.length === 0) return null;
150
+ return value.slice(0, 512);
151
+ }
152
+ function readUrl(fields, keys) {
153
+ const value = firstValue(fields, keys);
154
+ if (typeof value !== "string" || value.length === 0) return null;
155
+ return stripUrlDetails(value).slice(0, 512);
156
+ }
157
+ function readInteger(fields, keys) {
158
+ const value = firstValue(fields, keys);
159
+ return Number.isSafeInteger(value) ? value : null;
160
+ }
161
+ function normalizeViolation(fields) {
162
+ const violation = {
163
+ documentUri: readUrl(fields, [
164
+ "document-uri",
165
+ "documentURL",
166
+ "documentURI"
167
+ ]),
168
+ referrer: readUrl(fields, ["referrer"]),
169
+ blockedUri: readUrl(fields, [
170
+ "blocked-uri",
171
+ "blockedURL",
172
+ "blockedURI"
173
+ ]),
174
+ effectiveDirective: readText(fields, ["effective-directive", "effectiveDirective"]),
175
+ violatedDirective: readText(fields, ["violated-directive", "violatedDirective"]),
176
+ disposition: readText(fields, ["disposition"]),
177
+ sourceFile: readUrl(fields, ["source-file", "sourceFile"]),
178
+ lineNumber: readInteger(fields, ["line-number", "lineNumber"]),
179
+ columnNumber: readInteger(fields, ["column-number", "columnNumber"]),
180
+ statusCode: readInteger(fields, ["status-code", "statusCode"])
181
+ };
182
+ return violation.effectiveDirective ?? violation.violatedDirective ? violation : null;
183
+ }
184
+ function isCspEntry(entry) {
185
+ return isRecord(entry) && entry.type === CSP_REPORT_TYPE;
186
+ }
187
+ function extractFields(payload) {
188
+ if (Array.isArray(payload)) return payload.filter(isCspEntry).map((entry) => entry.body).filter(isRecord);
189
+ if (!isRecord(payload)) return null;
190
+ if (isRecord(payload["csp-report"])) return [payload["csp-report"]];
191
+ return isCspEntry(payload) && isRecord(payload.body) ? [payload.body] : [];
192
+ }
193
+ function parseJson(body) {
194
+ try {
195
+ return JSON.parse(body);
196
+ } catch {
197
+ return;
198
+ }
199
+ }
200
+ /**
201
+ * Parses a CSP violation report request. Returns at most 20 violations with
202
+ * every field cut to 512 characters and every URL stripped of query string,
203
+ * fragment, and credentials. Never throws: failures come back as a typed result.
204
+ */
205
+ function parseCspReports(input) {
206
+ if (!ACCEPTED_CONTENT_TYPES.has(contentTypeEssence(input.contentType))) return {
207
+ ok: false,
208
+ reason: "unsupported-content-type"
209
+ };
210
+ if (typeof input.body !== "string") return {
211
+ ok: false,
212
+ reason: "malformed-body"
213
+ };
214
+ const fieldSets = extractFields(parseJson(input.body));
215
+ if (fieldSets === null) return {
216
+ ok: false,
217
+ reason: "malformed-body"
218
+ };
219
+ return {
220
+ ok: true,
221
+ violations: fieldSets.slice(0, 20).map(normalizeViolation).filter((violation) => violation !== null)
222
+ };
223
+ }
224
+ // src/limits.ts
225
+ const PAYLOAD_TOO_LARGE_STATUS = 413;
226
+ /** Thrown when a request body is over the allowed size. Carries the HTTP status to answer with. */
227
+ var PayloadTooLargeError = class extends Error {
228
+ name = "PayloadTooLargeError";
229
+ status = PAYLOAD_TOO_LARGE_STATUS;
230
+ maxBytes;
231
+ constructor(maxBytes) {
232
+ super(`Request body is larger than ${maxBytes} bytes`);
233
+ this.maxBytes = maxBytes;
234
+ }
235
+ };
236
+ function assertValidLimit(maxBytes) {
237
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new TypeError(`maxBytes must be a non-negative integer, got ${maxBytes}`);
238
+ }
239
+ /** Throws a 413 error when a Content-Length header declares more than `maxBytes`. A missing or unparseable header passes: the body check still applies. */
240
+ function assertContentLengthWithinLimit(header, maxBytes) {
241
+ assertValidLimit(maxBytes);
242
+ if (!header || !/^\d+$/.test(header.trim())) return;
243
+ if (Number(header) > maxBytes) throw new PayloadTooLargeError(maxBytes);
244
+ }
245
+ /** Throws a 413 error when a body is larger than `maxBytes` (measured in bytes, not characters). */
246
+ function assertBodyWithinLimit(body, maxBytes) {
247
+ assertValidLimit(maxBytes);
248
+ if ((typeof body === "string" ? Buffer.byteLength(body) : body.byteLength) > maxBytes) throw new PayloadTooLargeError(maxBytes);
249
+ }
250
+ export { MAX_CSP_FIELD_LENGTH, MAX_CSP_VIOLATIONS, PayloadTooLargeError, assertBodyWithinLimit, assertContentLengthWithinLimit, buildContentSecurityPolicy, clerkOriginFromPublishableKey, generateCspNonce, mergeCspDirectives, nuxtReportOnlyPolicy, parseCspReports, securityHeaders, sentryOriginFromDsn, withReporting };
@@ -0,0 +1,32 @@
1
+ import { r as CspDirectives, s as SecurityHeadersOptions } from "./csp-Cpp1B3L9.js";
2
+ export interface WriteHeadersFileOptions extends Omit<SecurityHeadersOptions, "production"> {
3
+ /** Sources added to the built-in first-party policy. Must not allow `'unsafe-inline'` for scripts or styles. */
4
+ directives?: CspDirectives;
5
+ /** Where violation reports are sent. Adds `report-uri`, `report-to`, and `Reporting-Endpoints`. */
6
+ reportEndpoint?: string;
7
+ /** Add to an existing `_headers` file instead of refusing to overwrite it. */
8
+ append?: boolean;
9
+ /** Include the production-only headers (HSTS, X-Frame-Options). Defaults to true: the file is for a deployed build. */
10
+ production?: boolean;
11
+ }
12
+ export interface WriteHeadersFileResult {
13
+ path: string;
14
+ scriptHashes: string[];
15
+ styleHashes: string[];
16
+ }
17
+ export type HeadersFileErrorCode = "no-html" | "unhashable-inline" | "headers-file-exists" | "header-already-present" | "unsafe-inline-directive";
18
+ /** Thrown for every way writeHeadersFile refuses to write. `files` lists the offending paths. */
19
+ export declare class HeadersFileError extends Error {
20
+ name: string;
21
+ readonly code: HeadersFileErrorCode;
22
+ readonly files: readonly string[];
23
+ constructor(code: HeadersFileErrorCode, message: string, files?: readonly string[]);
24
+ }
25
+ /**
26
+ * Writes Netlify's `_headers` file for a built static site. Every inline
27
+ * `<script>` and `<style>` element is hashed (SHA-256), so the policy needs no
28
+ * `'unsafe-inline'`. Fails, naming the files, when the site has inline style
29
+ * attributes or event handlers; fails when there is no HTML; refuses to
30
+ * overwrite an existing `_headers` file unless `append` is set.
31
+ */
32
+ export declare function writeHeadersFile(outDir: string, options?: WriteHeadersFileOptions): Promise<WriteHeadersFileResult>;
@@ -0,0 +1,244 @@
1
+ import { existsSync } from "node:fs";
2
+ import { appendFile, readFile, readdir, writeFile } from "node:fs/promises";
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";
5
+ import { createHash } from "node:crypto";
6
+ // src/inline.ts
7
+ const HASH_ALGORITHM = "sha256";
8
+ const MIME_PARAMETER_SEPARATOR = ";";
9
+ const ELEMENT_OR_COMMENT_PATTERN = /<!--[\s\S]*?-->|<(script|style)\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/\1\s*>/gi;
10
+ const COMMENT_PATTERN = /<!--[\s\S]*?-->/g;
11
+ const LINE_BREAK_PATTERN = /\r\n?/g;
12
+ const JAVASCRIPT_URL_PATTERN = /^\s*javascript:/i;
13
+ const URL_IGNORED_CHARACTERS = /[\t\n\r]/g;
14
+ const URL_ATTRIBUTES = /* @__PURE__ */ new Set([
15
+ "href",
16
+ "src",
17
+ "action",
18
+ "formaction",
19
+ "xlink:href"
20
+ ]);
21
+ const NUMERIC_REFERENCE_PATTERN = /&#(?:x([0-9a-f]+)|(\d+));?/gi;
22
+ const NAMED_REFERENCES = {
23
+ "&tab;": "",
24
+ "&newline;": "",
25
+ "&colon;": ":"
26
+ };
27
+ const NAMED_REFERENCE_PATTERN = /&(?:tab|newline|colon);/gi;
28
+ const TAG_PATTERN = /<([a-zA-Z][^\s/>]*)((?:[^>"']|"[^"]*"|'[^']*')*)>/g;
29
+ const ATTRIBUTE_PATTERN = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
30
+ const EVENT_HANDLER_PATTERN = /^on[a-z]/i;
31
+ const EXECUTABLE_SCRIPT_TYPES = /* @__PURE__ */ new Set([
32
+ "",
33
+ "module",
34
+ "importmap",
35
+ "speculationrules",
36
+ "text/javascript",
37
+ "application/javascript",
38
+ "text/ecmascript",
39
+ "application/ecmascript",
40
+ "application/x-javascript",
41
+ "application/x-ecmascript",
42
+ "text/x-javascript",
43
+ "text/x-ecmascript",
44
+ "text/jscript",
45
+ "text/livescript",
46
+ "text/javascript1.0",
47
+ "text/javascript1.1",
48
+ "text/javascript1.2",
49
+ "text/javascript1.3",
50
+ "text/javascript1.4",
51
+ "text/javascript1.5"
52
+ ]);
53
+ const STYLE_TYPES = /* @__PURE__ */ new Set(["", "text/css"]);
54
+ function parseAttributes(attributes) {
55
+ const parsed = /* @__PURE__ */ new Map();
56
+ for (const match of attributes.matchAll(ATTRIBUTE_PATTERN)) {
57
+ const name = (match[1] ?? "").toLowerCase();
58
+ if (!parsed.has(name)) parsed.set(name, match[2] ?? match[3] ?? match[4] ?? "");
59
+ }
60
+ return parsed;
61
+ }
62
+ function declaredType(attributes) {
63
+ return ((attributes.get("type") ?? "").split(MIME_PARAMETER_SEPARATOR)[0] ?? "").trim().toLowerCase();
64
+ }
65
+ function hashSource(content) {
66
+ const digest = createHash(HASH_ALGORITHM).update(content.replace(LINE_BREAK_PATTERN, "\n"), "utf8").digest("base64");
67
+ return `'${HASH_ALGORITHM}-${digest}'`;
68
+ }
69
+ function isHashableScript(attributes) {
70
+ return !attributes.has("src") && EXECUTABLE_SCRIPT_TYPES.has(declaredType(attributes));
71
+ }
72
+ function isHashableStyle(attributes) {
73
+ return STYLE_TYPES.has(declaredType(attributes));
74
+ }
75
+ function decodeCharacterReferences(value) {
76
+ return value.replace(NUMERIC_REFERENCE_PATTERN, (_match, hex, decimal) => String.fromCodePoint(Number.parseInt(hex ?? decimal ?? "0", hex ? 16 : 10) % 1114112)).replace(NAMED_REFERENCE_PATTERN, (match) => NAMED_REFERENCES[match.toLowerCase()] ?? match);
77
+ }
78
+ function isUnhashable(name, value) {
79
+ if (name === "style" || EVENT_HANDLER_PATTERN.test(name)) return true;
80
+ return URL_ATTRIBUTES.has(name) && JAVASCRIPT_URL_PATTERN.test(decodeCharacterReferences(value).replace(URL_IGNORED_CHARACTERS, ""));
81
+ }
82
+ function unhashableAttributes(attributes) {
83
+ return [...parseAttributes(attributes)].filter(([name, value]) => isUnhashable(name, value)).map(([name]) => name);
84
+ }
85
+ function sortedUnique(values) {
86
+ return [...new Set(values)].sort();
87
+ }
88
+ /**
89
+ * Hashes every inline script and style element in an HTML document and lists
90
+ * the inline style attributes and event handlers that no hash can cover.
91
+ * The browser hashes the element's exact text, so content is never trimmed.
92
+ */
93
+ function findInlineSources(html) {
94
+ const scriptHashes = [];
95
+ const styleHashes = [];
96
+ const unhashable = [...html.replace(ELEMENT_OR_COMMENT_PATTERN, (match, tagName, attributes, content) => {
97
+ if (tagName === void 0) return match;
98
+ const isScript = tagName.toLowerCase() === "script";
99
+ if (isScript && isHashableScript(parseAttributes(attributes))) scriptHashes.push(hashSource(content));
100
+ if (!isScript && isHashableStyle(parseAttributes(attributes))) styleHashes.push(hashSource(content));
101
+ return `<${tagName}${attributes}>`;
102
+ }).replace(COMMENT_PATTERN, "").matchAll(TAG_PATTERN)].flatMap((tag) => unhashableAttributes(tag[2] ?? "").map((name) => `<${(tag[1] ?? "").toLowerCase()} ${name}>`));
103
+ return {
104
+ scriptHashes: sortedUnique(scriptHashes),
105
+ styleHashes: sortedUnique(styleHashes),
106
+ unhashable: sortedUnique(unhashable)
107
+ };
108
+ }
109
+ // src/netlify.ts
110
+ const HEADERS_FILENAME = "_headers";
111
+ const HTML_EXTENSION = ".html";
112
+ const HEADER_INDENT = " ";
113
+ const CSP_HEADER_NAME = "Content-Security-Policy";
114
+ const SCRIPT_HASH_DIRECTIVES = ["script-src", "script-src-elem"];
115
+ const STYLE_HASH_DIRECTIVES = ["style-src", "style-src-elem"];
116
+ const UNSAFE_INLINE_DIRECTIVES = [
117
+ ...SCRIPT_HASH_DIRECTIVES,
118
+ ...STYLE_HASH_DIRECTIVES,
119
+ "script-src-attr",
120
+ "style-src-attr"
121
+ ];
122
+ const BASE_DIRECTIVES = {
123
+ "default-src": [SELF_SOURCE],
124
+ "script-src": [SELF_SOURCE],
125
+ "style-src": [SELF_SOURCE],
126
+ "object-src": [NONE_SOURCE],
127
+ "base-uri": [SELF_SOURCE],
128
+ "form-action": [SELF_SOURCE],
129
+ "frame-ancestors": [NONE_SOURCE]
130
+ };
131
+ /** Thrown for every way writeHeadersFile refuses to write. `files` lists the offending paths. */
132
+ var HeadersFileError = class extends Error {
133
+ name = "HeadersFileError";
134
+ code;
135
+ files;
136
+ constructor(code, message, files = []) {
137
+ super(message);
138
+ this.code = code;
139
+ this.files = files;
140
+ }
141
+ };
142
+ async function findHtmlFiles(outDir) {
143
+ return (await readdir(outDir, {
144
+ recursive: true,
145
+ withFileTypes: true
146
+ }).catch((error) => {
147
+ if (error.code === "ENOENT") return [];
148
+ throw error;
149
+ })).filter((entry) => entry.isFile() && entry.name.endsWith(HTML_EXTENSION)).map((entry) => join(entry.parentPath, entry.name)).sort();
150
+ }
151
+ function assertNoUnsafeInline(directives) {
152
+ const offending = UNSAFE_INLINE_DIRECTIVES.filter((name) => directives[name]?.some((source) => source.toLowerCase() === UNSAFE_INLINE_SOURCE));
153
+ if (offending.length === 0) return;
154
+ throw new HeadersFileError("unsafe-inline-directive", `directives must not allow 'unsafe-inline' in ${offending.join(", ")}: the hashes replace it`);
155
+ }
156
+ function formatHeadersBlock(headers) {
157
+ return `/*\n${Object.entries(headers).map(([name, value]) => `${HEADER_INDENT}${name}: ${value}`).join("\n")}\n`;
158
+ }
159
+ function hashDirectives(supplied, scriptHashes, styleHashes) {
160
+ const directives = {
161
+ "script-src": scriptHashes,
162
+ "style-src": styleHashes
163
+ };
164
+ if (supplied["script-src-elem"]) directives["script-src-elem"] = scriptHashes;
165
+ if (supplied["style-src-elem"]) directives["style-src-elem"] = styleHashes;
166
+ return directives;
167
+ }
168
+ function buildHeaders(options, scriptHashes, styleHashes) {
169
+ const directives = mergeCspDirectives(BASE_DIRECTIVES, options.directives ?? {}, hashDirectives(options.directives ?? {}, scriptHashes, styleHashes));
170
+ const policy = buildContentSecurityPolicy(directives);
171
+ const headers = securityHeaders({
172
+ production: options.production ?? true,
173
+ hstsPreload: options.hstsPreload,
174
+ extraDeniedFeatures: options.extraDeniedFeatures
175
+ });
176
+ if (!options.reportEndpoint) return {
177
+ ...headers,
178
+ [CSP_HEADER_NAME]: policy
179
+ };
180
+ const reporting = withReporting(policy, { endpoint: options.reportEndpoint });
181
+ return {
182
+ ...headers,
183
+ [CSP_HEADER_NAME]: reporting.policy,
184
+ [REPORTING_ENDPOINTS_HEADER]: reporting.reportingEndpoints
185
+ };
186
+ }
187
+ function existingHeaderNames(content) {
188
+ const names = content.split("\n").filter((line) => /^\s+\S/.test(line)).map((line) => line.slice(0, line.indexOf(":")).trim().toLowerCase());
189
+ return new Set(names);
190
+ }
191
+ async function persistBlock(headersPath, block, headerNames) {
192
+ if (!existsSync(headersPath)) {
193
+ await writeFile(headersPath, block, { flag: "wx" });
194
+ return;
195
+ }
196
+ const existing = existingHeaderNames(await readFile(headersPath, "utf8"));
197
+ const duplicated = headerNames.filter((name) => existing.has(name.toLowerCase()));
198
+ if (duplicated.length > 0) throw new HeadersFileError("header-already-present", `${HEADERS_FILENAME} already sets ${duplicated.join(", ")}; appending would send both values`, [HEADERS_FILENAME]);
199
+ await appendFile(headersPath, `\n${block}`);
200
+ }
201
+ async function scanSite(outDir) {
202
+ const htmlFiles = await findHtmlFiles(outDir);
203
+ if (htmlFiles.length === 0) throw new HeadersFileError("no-html", `No HTML files found in ${outDir}`);
204
+ const scriptHashes = /* @__PURE__ */ new Set();
205
+ const styleHashes = /* @__PURE__ */ new Set();
206
+ const unhashableFiles = /* @__PURE__ */ new Set();
207
+ const unhashableDetails = [];
208
+ for (const file of htmlFiles) {
209
+ const findings = findInlineSources(await readFile(file, "utf8"));
210
+ findings.scriptHashes.forEach((hash) => scriptHashes.add(hash));
211
+ 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}`));
215
+ }
216
+ return {
217
+ scriptHashes: [...scriptHashes].sort(),
218
+ styleHashes: [...styleHashes].sort(),
219
+ unhashableFiles: [...unhashableFiles],
220
+ unhashableDetails
221
+ };
222
+ }
223
+ /**
224
+ * Writes Netlify's `_headers` file for a built static site. Every inline
225
+ * `<script>` and `<style>` element is hashed (SHA-256), so the policy needs no
226
+ * `'unsafe-inline'`. Fails, naming the files, when the site has inline style
227
+ * attributes or event handlers; fails when there is no HTML; refuses to
228
+ * overwrite an existing `_headers` file unless `append` is set.
229
+ */
230
+ async function writeHeadersFile(outDir, options = {}) {
231
+ assertNoUnsafeInline(options.directives ?? {});
232
+ const headersPath = join(outDir, HEADERS_FILENAME);
233
+ 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
+ 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);
236
+ const headers = buildHeaders(options, site.scriptHashes, site.styleHashes);
237
+ await persistBlock(headersPath, formatHeadersBlock(headers), Object.keys(headers));
238
+ return {
239
+ path: headersPath,
240
+ scriptHashes: site.scriptHashes,
241
+ styleHashes: site.styleHashes
242
+ };
243
+ }
244
+ export { HeadersFileError, writeHeadersFile };
@@ -0,0 +1,108 @@
1
+ import { randomBytes } from "node:crypto";
2
+ // src/headers.ts
3
+ const BASE_DENIED_FEATURES = [
4
+ "camera",
5
+ "microphone",
6
+ "geolocation"
7
+ ];
8
+ const HSTS_MAX_AGE_SECONDS = 63072e3;
9
+ const FEATURE_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
10
+ function permissionsPolicy(extraDeniedFeatures) {
11
+ return [.../* @__PURE__ */ new Set([...BASE_DENIED_FEATURES, ...extraDeniedFeatures])].map((feature) => {
12
+ if (!FEATURE_NAME_PATTERN.test(feature)) throw new TypeError(`Invalid Permissions-Policy feature: ${feature}`);
13
+ return `${feature}=()`;
14
+ }).join(", ");
15
+ }
16
+ function strictTransportSecurity(hstsPreload) {
17
+ const base = `max-age=${HSTS_MAX_AGE_SECONDS}; includeSubDomains`;
18
+ return hstsPreload ? `${base}; preload` : base;
19
+ }
20
+ /** Returns the baseline security response headers as a plain record. */
21
+ function securityHeaders(options = {}) {
22
+ const headers = {
23
+ "X-Content-Type-Options": "nosniff",
24
+ "Referrer-Policy": "strict-origin-when-cross-origin",
25
+ "Permissions-Policy": permissionsPolicy(options.extraDeniedFeatures ?? [])
26
+ };
27
+ if (!options.production) return headers;
28
+ headers["Strict-Transport-Security"] = strictTransportSecurity(Boolean(options.hstsPreload));
29
+ headers["X-Frame-Options"] = "DENY";
30
+ return headers;
31
+ }
32
+ // src/csp.ts
33
+ const NONCE_BYTE_LENGTH = 16;
34
+ const SCRIPT_SRC = "script-src";
35
+ const DEFAULT_SRC = "default-src";
36
+ const SELF_SOURCE = "'self'";
37
+ const NONE_SOURCE = "'none'";
38
+ const UNSAFE_INLINE_SOURCE = "'unsafe-inline'";
39
+ const SCRIPT_SRC_ELEM = "script-src-elem";
40
+ const DIRECTIVE_NAME_PATTERN = /^[a-z][a-z-]*$/;
41
+ const NONCE_PATTERN = /^[A-Za-z0-9+/_-]+=*$/;
42
+ /** Returns a fresh nonce: 16 random bytes, base64 encoded. */
43
+ function generateCspNonce() {
44
+ return randomBytes(NONCE_BYTE_LENGTH).toString("base64");
45
+ }
46
+ function unique(sources) {
47
+ return [...new Set(sources)];
48
+ }
49
+ /** Merges directive maps left to right, de-duplicating the sources of each directive. */
50
+ function mergeCspDirectives(...maps) {
51
+ const merged = {};
52
+ const entries = maps.flatMap((map) => Object.entries(map));
53
+ for (const [name, sources] of entries) {
54
+ if (sources === void 0) continue;
55
+ merged[name] = unique([...merged[name] ?? [], ...sources]);
56
+ }
57
+ return merged;
58
+ }
59
+ function validateSource(source) {
60
+ if (/[;,\s]/.test(source) || source.length === 0) throw new TypeError(`Invalid CSP source: ${JSON.stringify(source)}`);
61
+ }
62
+ function withoutRedundantNone(sources) {
63
+ if (sources.length === 1) return [...sources];
64
+ return sources.filter((source) => source !== NONE_SOURCE);
65
+ }
66
+ function serializeDirective(name, sources) {
67
+ if (!DIRECTIVE_NAME_PATTERN.test(name)) throw new TypeError(`Invalid CSP directive name: ${JSON.stringify(name)}`);
68
+ sources.forEach(validateSource);
69
+ return [name, ...withoutRedundantNone(unique(sources))].join(" ");
70
+ }
71
+ function addNonce(directives, nonce) {
72
+ if (!NONCE_PATTERN.test(nonce)) throw new TypeError("Invalid CSP nonce");
73
+ const nonceSource = `'nonce-${nonce}'`;
74
+ const inherited = directives[SCRIPT_SRC] ?? directives[DEFAULT_SRC] ?? [];
75
+ const withNonce = {
76
+ ...directives,
77
+ [SCRIPT_SRC]: [...inherited, nonceSource]
78
+ };
79
+ const elementSources = directives[SCRIPT_SRC_ELEM];
80
+ if (elementSources) withNonce[SCRIPT_SRC_ELEM] = [...elementSources, nonceSource];
81
+ return withNonce;
82
+ }
83
+ /** Turns a directive map into a Content-Security-Policy string. */
84
+ function buildContentSecurityPolicy(directives, options = {}) {
85
+ const resolved = options.nonce ? addNonce(directives, options.nonce) : directives;
86
+ return Object.entries(resolved).filter(([, sources]) => sources !== void 0).map(([name, sources = []]) => serializeDirective(name, sources)).join("; ");
87
+ }
88
+ // src/reporting.ts
89
+ const DEFAULT_GROUP = "csp-endpoint";
90
+ const GROUP_PATTERN = /^[A-Za-z0-9_-]+$/;
91
+ const FORBIDDEN_ENDPOINT_PATTERN = /["\s;,\\]|[^\x20-\x7e]/;
92
+ const REPORTING_ENDPOINTS_HEADER = "Reporting-Endpoints";
93
+ function withoutReportingDirectives(policy) {
94
+ return policy.split(";").map((directive) => directive.trim()).filter((directive) => directive.length > 0).filter((directive) => !/^report-(?:uri|to)(?:\s|$)/i.test(directive)).join("; ");
95
+ }
96
+ /** Adds `report-uri` and `report-to` to a policy and returns the matching `Reporting-Endpoints` value. */
97
+ function withReporting(policy, options) {
98
+ const group = options.group ?? DEFAULT_GROUP;
99
+ if (!GROUP_PATTERN.test(group)) throw new TypeError(`Invalid reporting group: ${JSON.stringify(group)}`);
100
+ if (!options.endpoint || FORBIDDEN_ENDPOINT_PATTERN.test(options.endpoint)) throw new TypeError(`Invalid reporting endpoint: ${JSON.stringify(options.endpoint)}`);
101
+ const base = withoutReportingDirectives(policy);
102
+ const reporting = `report-uri ${options.endpoint}; report-to ${group}`;
103
+ return {
104
+ policy: base ? `${base}; ${reporting}` : reporting,
105
+ reportingEndpoints: `${group}="${options.endpoint}"`
106
+ };
107
+ }
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 };
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@neon-pixels/security",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Security response headers, a Content-Security-Policy builder, a hashed policy build step for static sites, and CSP report parsing.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/neonpixels-studio/packages.git",
10
+ "directory": "packages/security"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./netlify": {
18
+ "types": "./dist/netlify.d.ts",
19
+ "default": "./dist/netlify.js"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "engines": {
30
+ "node": "^22.17.0 || ^24.0.0 || >=26.0.0"
31
+ },
32
+ "scripts": {
33
+ "build": "tsdown",
34
+ "typecheck": "tsc --noEmit -p tsconfig.json"
35
+ }
6
36
  }