@cbrl/next 0.0.0-stage → 0.1.1

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 Kayron Cabral
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,162 @@
1
- # Temporary Holding Version
1
+ # @cbrl/next
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
+ Building blocks every Next.js 16 app here repeats, in one place:
4
+
5
+ - **`@cbrl/next/config`** (Node-only, for `next.config.ts`): a shared CSP baseline,
6
+ the security header set with **CSP reporting that actually reports**, the build
7
+ commit SHA and the dev origins allowlist.
8
+ - **`@cbrl/next/server`** (Route Handlers): an uncached `/api/health` and a CSP
9
+ report endpoint that strips personal data from reported URLs.
10
+ - **`@cbrl/next`** (isomorphic, safe in Client Components): `safeNext`, the
11
+ open-redirect guard for `?next=` params.
12
+
13
+ ```sh
14
+ pnpm add @cbrl/next
15
+ ```
16
+
17
+ Peer dependency: `next ^16`.
18
+
19
+ ## `next.config.ts`
20
+
21
+ ```ts
22
+ import { commitSha, cspDirectives, devOrigins, withSecurityHeaders } from '@cbrl/next/config'
23
+ import type { NextConfig } from 'next'
24
+
25
+ const supabaseOrigin = process.env.NEXT_PUBLIC_SUPABASE_URL
26
+ ? new URL(process.env.NEXT_PUBLIC_SUPABASE_URL).origin
27
+ : 'https://*.supabase.co'
28
+
29
+ const nextConfig: NextConfig = {
30
+ typedRoutes: true,
31
+ // Served by /api/health so a smoke test can check which commit is live.
32
+ env: { NEXT_PUBLIC_COMMIT_SHA: commitSha() },
33
+ // 127.0.0.1, <hostname>.local and the machine's LAN IPv4s.
34
+ allowedDevOrigins: devOrigins(),
35
+ }
36
+
37
+ export default withSecurityHeaders(nextConfig, {
38
+ csp: cspDirectives({
39
+ 'connect-src': [supabaseOrigin],
40
+ 'form-action': ['https://checkout.stripe.com'],
41
+ }),
42
+ cspMode: 'report-only',
43
+ reportPath: '/api/csp-report',
44
+ })
45
+ ```
46
+
47
+ `withSecurityHeaders` sets `poweredByHeader: false` and prepends one rule
48
+ (`source: '/:path*'` by default) to whatever `headers()` the config already has, so
49
+ an app rule for the same header key on a narrower path still wins.
50
+
51
+ ### The CSP baseline
52
+
53
+ `cspDirectives(additions)` starts from:
54
+
55
+ ```
56
+ default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';
57
+ img-src 'self' data: https: blob:; font-src 'self' data:; connect-src 'self';
58
+ worker-src 'self' blob:; frame-src 'none'; frame-ancestors 'none'; object-src 'none';
59
+ base-uri 'self'; form-action 'self'
60
+ ```
61
+
62
+ Additions are appended to the directive of the same name (keys are the CSP
63
+ directive names). Adding to a directive whose baseline is `'none'`, such as
64
+ `frame-src`, replaces the `'none'`. Unknown directives are added as given, with an
65
+ empty list emitting a bare directive (`'upgrade-insecure-requests': []`).
66
+ `buildCsp(directives)` serializes any directive map if you need the string.
67
+
68
+ ### Headers
69
+
70
+ `securityHeaders({ csp, cspMode, reportPath })` returns:
71
+
72
+ | Header | Value |
73
+ | ----------------------------------------------------------------- | --------------------------------------------------------------- |
74
+ | `Strict-Transport-Security` | `max-age=31536000; includeSubDomains; preload` |
75
+ | `X-Content-Type-Options` | `nosniff` |
76
+ | `X-Frame-Options` | `DENY` |
77
+ | `Referrer-Policy` | `strict-origin-when-cross-origin` |
78
+ | `Permissions-Policy` | `camera=(), microphone=(), geolocation=(), interest-cohort=()` |
79
+ | `Content-Security-Policy-Report-Only` / `Content-Security-Policy` | the CSP, plus `report-uri <reportPath>; report-to csp-endpoint` |
80
+ | `Reporting-Endpoints` (only with `reportPath`) | `csp-endpoint="<reportPath>"` |
81
+
82
+ A report-only CSP **without** `reportPath` blocks nothing and reports nothing; it
83
+ is only useful in the browser console. Always pass `reportPath`. Both `report-uri`
84
+ (Firefox, Safari) and `report-to` (Chromium) are emitted.
85
+
86
+ ## Route Handlers
87
+
88
+ ```ts
89
+ // app/api/health/route.ts
90
+ import { healthRoute } from '@cbrl/next/server'
91
+
92
+ import { pool } from '@/lib/db'
93
+
94
+ export const GET = healthRoute({
95
+ ping: () => pool.query('SELECT 1'),
96
+ timeoutMs: 4000,
97
+ onError: (error) => logger.error({ err: error }, 'health ping failed'),
98
+ })
99
+ ```
100
+
101
+ Responds `{ status: 'ok' | 'error', commit, database: 'ok' | 'unreachable' }` with
102
+ 200 or 503. `commit` is `NEXT_PUBLIC_COMMIT_SHA`, else `VERCEL_GIT_COMMIT_SHA`, else
103
+ `null`. The handler awaits `connection()`, so it is never prerendered with Cache
104
+ Components, and sends `Cache-Control: no-store`. A ping that hangs longer than
105
+ `timeoutMs` counts as unreachable.
106
+
107
+ ```ts
108
+ // app/api/csp-report/route.ts
109
+ import { cspReportRoute } from '@cbrl/next/server'
110
+
111
+ export const POST = cspReportRoute({
112
+ onReport: (violation) => logger.warn(violation, 'csp violation'),
113
+ })
114
+ ```
115
+
116
+ Accepts `application/csp-report` (`report-uri`), `application/reports+json`
117
+ (`report-to`) and `application/json`; anything else gets 415. Bodies over
118
+ `maxBytes` (64 KiB by default) get 413, invalid JSON 400, otherwise 204. Each
119
+ violation reaches `onReport` as:
120
+
121
+ ```ts
122
+ interface CspViolation {
123
+ documentUri: string // origin + path
124
+ blockedUri: string // origin + path, a scheme such as `data`, or `inline` / `eval`
125
+ violatedDirective: string
126
+ disposition: 'enforce' | 'report'
127
+ sourceFile?: string
128
+ lineNumber?: number
129
+ columnNumber?: number
130
+ }
131
+ ```
132
+
133
+ Query strings and fragments are stripped from every URI and the referrer, script
134
+ sample and user agent are dropped: URLs routinely carry tokens, emails and search
135
+ terms, and violation logs must not become a store of personal data (LGPD). The
136
+ endpoint is public by design (browsers send reports without credentials), so make
137
+ sure your `proxy.ts` does not require a session on it.
138
+
139
+ ## `safeNext`
140
+
141
+ ```ts
142
+ import { safeNext } from '@cbrl/next'
143
+
144
+ redirect(safeNext(searchParams.get('next'), '/dashboard'))
145
+ const next = safeNext(raw, null) // string | null
146
+ ```
147
+
148
+ Returns `raw` only when it is a same-origin path: starts with `/`, not `//` or
149
+ `/\`, no control characters (browsers strip tabs and newlines, turning `/\t/evil.com`
150
+ into `//evil.com`). Otherwise returns `fallback`. `isSafeInternalPath(raw)` is the
151
+ underlying type guard.
152
+
153
+ ## Rolling out an enforced CSP
154
+
155
+ 1. Ship `cspMode: 'report-only'` **with** `reportPath` and the `cspReportRoute`
156
+ endpoint.
157
+ 2. Watch the reports through real traffic for a while (include auth, checkout and
158
+ any third-party flows). For each legitimate violation, add the source to
159
+ `cspDirectives(...)`; ignore noise from browser extensions (`chrome-extension`,
160
+ `moz-extension` blocked URIs).
161
+ 3. When the reports have run clean, switch to `cspMode: 'enforce'` and keep
162
+ `reportPath`, so regressions keep being reported after they start being blocked.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * `next.config.ts` helpers (Node-only): CSP builder, security headers with real
3
+ * CSP reporting, build commit SHA and dev origins.
4
+ */
5
+ import { NextConfig } from "next";
6
+ /** CSP directive names with editor autocompletion; any other directive name is accepted too. */
7
+ type CspDirectiveName = 'default-src' | 'script-src' | 'style-src' | 'img-src' | 'font-src' | 'connect-src' | 'media-src' | 'worker-src' | 'manifest-src' | 'frame-src' | 'frame-ancestors' | 'object-src' | 'base-uri' | 'form-action' | 'upgrade-insecure-requests' | 'report-uri' | 'report-to' | (string & {});
8
+ /**
9
+ * A CSP as a map of directive name to source list. An empty list emits the bare
10
+ * directive (for value-less directives such as `upgrade-insecure-requests`).
11
+ */
12
+ type CspDirectives = Partial<Record<CspDirectiveName, readonly string[]>>;
13
+ /**
14
+ * Serialize directives into a CSP header value. Sources are de-duplicated and
15
+ * directives keep insertion order.
16
+ *
17
+ * @example buildCsp({ 'default-src': ["'self'"] }) // "default-src 'self'"
18
+ */
19
+ export declare function buildCsp(directives: CspDirectives): string;
20
+ /**
21
+ * The shared baseline CSP merged with app-specific sources. Additions are
22
+ * appended to the baseline list of the same directive; adding to a directive
23
+ * whose baseline is `'none'` (e.g. `frame-src`) replaces the `'none'`.
24
+ * Directives not in the baseline are added as given; an empty list leaves a
25
+ * baseline directive untouched.
26
+ *
27
+ * @example
28
+ * cspDirectives({
29
+ * 'connect-src': ['https://abc.supabase.co'],
30
+ * 'frame-src': ['https://challenges.cloudflare.com'],
31
+ * })
32
+ */
33
+ export declare function cspDirectives(additions?: CspDirectives): CspDirectives;
34
+ /** One `{ key, value }` response header, as Next.js `headers()` expects. */
35
+ interface SecurityHeader {
36
+ key: string;
37
+ value: string;
38
+ }
39
+ /** Options for {@link securityHeaders} and {@link withSecurityHeaders}. */
40
+ interface SecurityHeadersOptions {
41
+ /** CSP directives, usually from `cspDirectives()`. */
42
+ csp: CspDirectives;
43
+ /**
44
+ * `'report-only'` sends `Content-Security-Policy-Report-Only` (violations are
45
+ * reported, nothing is blocked); `'enforce'` sends `Content-Security-Policy`.
46
+ * Defaults to `'report-only'`.
47
+ */
48
+ cspMode?: 'report-only' | 'enforce';
49
+ /**
50
+ * Where browsers POST violation reports, e.g. `'/api/csp-report'` (served by
51
+ * `cspReportRoute()`) or an absolute `https://` URL. Adds `report-uri` and
52
+ * `report-to` to the CSP plus a `Reporting-Endpoints` header. Without it the
53
+ * report-only mode reports nothing.
54
+ */
55
+ reportPath?: string;
56
+ }
57
+ /** Options for {@link withSecurityHeaders}. */
58
+ interface WithSecurityHeadersOptions extends SecurityHeadersOptions {
59
+ /** Path pattern the headers apply to. Defaults to every path, `'/:path*'`. */
60
+ source?: string;
61
+ }
62
+ /** Reporting API endpoint group named by `report-to`. */
63
+ export declare const CSP_REPORT_GROUP = "csp-endpoint";
64
+ /**
65
+ * The security header set: HSTS (1 year, subdomains, preload),
66
+ * `nosniff`, `X-Frame-Options: DENY`, a strict referrer policy, a restrictive
67
+ * `Permissions-Policy` and the CSP (report-only or enforced), wired to a
68
+ * report endpoint when `reportPath` is given.
69
+ */
70
+ export declare function securityHeaders(options: SecurityHeadersOptions): SecurityHeader[];
71
+ /**
72
+ * Wrap a Next.js config so every response carries {@link securityHeaders} and
73
+ * the `X-Powered-By` header is dropped. Header rules the config already
74
+ * declares are kept and come after ours, so an app rule for the same key wins.
75
+ */
76
+ export declare function withSecurityHeaders(nextConfig: NextConfig, options: WithSecurityHeadersOptions): NextConfig;
77
+ /**
78
+ * The commit being built, for `env.NEXT_PUBLIC_COMMIT_SHA` in `next.config.ts`.
79
+ * Resolution order: `NEXT_PUBLIC_COMMIT_SHA`, `VERCEL_GIT_COMMIT_SHA`,
80
+ * `git rev-parse HEAD`, then the literal `'unknown'` so builds without a
81
+ * readable `.git` do not crash.
82
+ */
83
+ export declare function commitSha(): string;
84
+ /**
85
+ * Hostnames for `allowedDevOrigins`: `127.0.0.1` (Playwright), this machine's
86
+ * mDNS name (`<hostname>.local`, lowercased because origin matching is
87
+ * case-sensitive), every non-internal LAN IPv4 (resolved at startup, so DHCP
88
+ * changes do not break phone testing) and `extra`. Next.js dev blocks
89
+ * cross-origin `/_next/*` requests from unlisted hosts, which silently stalls
90
+ * hydration.
91
+ */
92
+ export declare function devOrigins(extra?: readonly string[]): string[];
93
+ export type { CspDirectiveName, CspDirectives, SecurityHeader, SecurityHeadersOptions, WithSecurityHeadersOptions };
@@ -0,0 +1,172 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { hostname, networkInterfaces } from "node:os";
3
+ // src/config/csp.ts
4
+ /**
5
+ * The shared baseline: same-origin by default, no framing by other sites, no
6
+ * plugins, no `<base>` hijacking, forms post same-origin. Inline scripts/styles
7
+ * stay allowed because Next.js App Router injects inline bootstrap code.
8
+ */
9
+ const BASELINE = {
10
+ "default-src": ["'self'"],
11
+ "script-src": ["'self'", "'unsafe-inline'"],
12
+ "style-src": ["'self'", "'unsafe-inline'"],
13
+ "img-src": [
14
+ "'self'",
15
+ "data:",
16
+ "https:",
17
+ "blob:"
18
+ ],
19
+ "font-src": ["'self'", "data:"],
20
+ "connect-src": ["'self'"],
21
+ "worker-src": ["'self'", "blob:"],
22
+ "frame-src": ["'none'"],
23
+ "frame-ancestors": ["'none'"],
24
+ "object-src": ["'none'"],
25
+ "base-uri": ["'self'"],
26
+ "form-action": ["'self'"]
27
+ };
28
+ const NONE = "'none'";
29
+ function unique(values) {
30
+ return [...new Set(values)];
31
+ }
32
+ /**
33
+ * Serialize directives into a CSP header value. Sources are de-duplicated and
34
+ * directives keep insertion order.
35
+ *
36
+ * @example buildCsp({ 'default-src': ["'self'"] }) // "default-src 'self'"
37
+ */
38
+ function buildCsp(directives) {
39
+ return Object.entries(directives).flatMap(([name, sources]) => {
40
+ if (sources === void 0) return [];
41
+ const list = unique(sources);
42
+ return [list.length === 0 ? name : `${name} ${list.join(" ")}`];
43
+ }).join("; ");
44
+ }
45
+ /**
46
+ * The shared baseline CSP merged with app-specific sources. Additions are
47
+ * appended to the baseline list of the same directive; adding to a directive
48
+ * whose baseline is `'none'` (e.g. `frame-src`) replaces the `'none'`.
49
+ * Directives not in the baseline are added as given; an empty list leaves a
50
+ * baseline directive untouched.
51
+ *
52
+ * @example
53
+ * cspDirectives({
54
+ * 'connect-src': ['https://abc.supabase.co'],
55
+ * 'frame-src': ['https://challenges.cloudflare.com'],
56
+ * })
57
+ */
58
+ function cspDirectives(additions = {}) {
59
+ const merged = { ...BASELINE };
60
+ for (const [name, sources] of Object.entries(additions)) {
61
+ const base = merged[name];
62
+ if (sources === void 0 || base !== void 0 && sources.length === 0) continue;
63
+ merged[name] = unique([...(base ?? []).filter((source) => source !== NONE), ...sources]);
64
+ }
65
+ return merged;
66
+ }
67
+ // src/config/headers.ts
68
+ /** Reporting API endpoint group named by `report-to`. */
69
+ const CSP_REPORT_GROUP = "csp-endpoint";
70
+ /**
71
+ * The security header set: HSTS (1 year, subdomains, preload),
72
+ * `nosniff`, `X-Frame-Options: DENY`, a strict referrer policy, a restrictive
73
+ * `Permissions-Policy` and the CSP (report-only or enforced), wired to a
74
+ * report endpoint when `reportPath` is given.
75
+ */
76
+ function securityHeaders(options) {
77
+ const { csp, cspMode = "report-only", reportPath } = options;
78
+ const directives = reportPath === void 0 ? csp : {
79
+ ...csp,
80
+ "report-uri": [reportPath],
81
+ "report-to": [CSP_REPORT_GROUP]
82
+ };
83
+ const headers = [
84
+ {
85
+ key: "Strict-Transport-Security",
86
+ value: "max-age=31536000; includeSubDomains; preload"
87
+ },
88
+ {
89
+ key: "X-Content-Type-Options",
90
+ value: "nosniff"
91
+ },
92
+ {
93
+ key: "X-Frame-Options",
94
+ value: "DENY"
95
+ },
96
+ {
97
+ key: "Referrer-Policy",
98
+ value: "strict-origin-when-cross-origin"
99
+ },
100
+ {
101
+ key: "Permissions-Policy",
102
+ value: "camera=(), microphone=(), geolocation=(), interest-cohort=()"
103
+ },
104
+ {
105
+ key: cspMode === "enforce" ? "Content-Security-Policy" : "Content-Security-Policy-Report-Only",
106
+ value: buildCsp(directives)
107
+ }
108
+ ];
109
+ if (reportPath !== void 0) headers.push({
110
+ key: "Reporting-Endpoints",
111
+ value: `${CSP_REPORT_GROUP}="${reportPath}"`
112
+ });
113
+ return headers;
114
+ }
115
+ /**
116
+ * Wrap a Next.js config so every response carries {@link securityHeaders} and
117
+ * the `X-Powered-By` header is dropped. Header rules the config already
118
+ * declares are kept and come after ours, so an app rule for the same key wins.
119
+ */
120
+ function withSecurityHeaders(nextConfig, options) {
121
+ const { source = "/:path*", ...headerOptions } = options;
122
+ const ownHeaders = nextConfig.headers;
123
+ return {
124
+ ...nextConfig,
125
+ poweredByHeader: false,
126
+ async headers() {
127
+ const existing = ownHeaders ? await ownHeaders() : [];
128
+ return [{
129
+ source,
130
+ headers: securityHeaders(headerOptions)
131
+ }, ...existing];
132
+ }
133
+ };
134
+ }
135
+ // src/config/runtime.ts
136
+ /**
137
+ * The commit being built, for `env.NEXT_PUBLIC_COMMIT_SHA` in `next.config.ts`.
138
+ * Resolution order: `NEXT_PUBLIC_COMMIT_SHA`, `VERCEL_GIT_COMMIT_SHA`,
139
+ * `git rev-parse HEAD`, then the literal `'unknown'` so builds without a
140
+ * readable `.git` do not crash.
141
+ */
142
+ function commitSha() {
143
+ const fromEnv = process.env.NEXT_PUBLIC_COMMIT_SHA || process.env.VERCEL_GIT_COMMIT_SHA;
144
+ if (fromEnv) return fromEnv;
145
+ try {
146
+ return execFileSync("git", ["rev-parse", "HEAD"], { stdio: [
147
+ "ignore",
148
+ "pipe",
149
+ "ignore"
150
+ ] }).toString().trim();
151
+ } catch {
152
+ return "unknown";
153
+ }
154
+ }
155
+ /**
156
+ * Hostnames for `allowedDevOrigins`: `127.0.0.1` (Playwright), this machine's
157
+ * mDNS name (`<hostname>.local`, lowercased because origin matching is
158
+ * case-sensitive), every non-internal LAN IPv4 (resolved at startup, so DHCP
159
+ * changes do not break phone testing) and `extra`. Next.js dev blocks
160
+ * cross-origin `/_next/*` requests from unlisted hosts, which silently stalls
161
+ * hydration.
162
+ */
163
+ function devOrigins(extra = []) {
164
+ const lan = Object.values(networkInterfaces()).flatMap((infos = []) => infos).flatMap((info) => info.family === "IPv4" && !info.internal ? [info.address] : []);
165
+ return [.../* @__PURE__ */ new Set([
166
+ "127.0.0.1",
167
+ `${hostname().toLowerCase()}.local`,
168
+ ...lan,
169
+ ...extra
170
+ ])];
171
+ }
172
+ export { CSP_REPORT_GROUP, buildCsp, commitSha, cspDirectives, devOrigins, securityHeaders, withSecurityHeaders };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Isomorphic helpers, safe to import from Client Components.
3
+ */
4
+ /**
5
+ * Whether `raw` is a same-origin path: a string starting with a single `/`.
6
+ * Rejects absolute URLs, protocol-relative `//host`, `/\host` (browsers treat
7
+ * `\` as `/`) and control characters (browsers strip tabs/newlines, so
8
+ * `/\t/host` would become `//host`).
9
+ */
10
+ export declare function isSafeInternalPath(raw: unknown): raw is string;
11
+ /**
12
+ * The redirect target from an untrusted `next` param when it is a same-origin
13
+ * path, otherwise `fallback` — so a crafted link cannot bounce the user
14
+ * off-site after sign-in.
15
+ *
16
+ * @example safeNext(searchParams.get('next'), '/dashboard')
17
+ * @example safeNext(searchParams.get('next'), null) // null when unsafe
18
+ */
19
+ export declare function safeNext<const F extends string | null>(raw: unknown, fallback: F): string | F;
package/dist/index.mjs ADDED
@@ -0,0 +1,32 @@
1
+ // src/index.ts
2
+ /**
3
+ * Isomorphic helpers, safe to import from Client Components.
4
+ */
5
+ function hasControlChar(value) {
6
+ for (let index = 0; index < value.length; index++) {
7
+ const code = value.charCodeAt(index);
8
+ if (code < 32 || code === 127) return true;
9
+ }
10
+ return false;
11
+ }
12
+ /**
13
+ * Whether `raw` is a same-origin path: a string starting with a single `/`.
14
+ * Rejects absolute URLs, protocol-relative `//host`, `/\host` (browsers treat
15
+ * `\` as `/`) and control characters (browsers strip tabs/newlines, so
16
+ * `/\t/host` would become `//host`).
17
+ */
18
+ function isSafeInternalPath(raw) {
19
+ return typeof raw === "string" && raw.startsWith("/") && !raw.startsWith("//") && !raw.startsWith("/\\") && !hasControlChar(raw);
20
+ }
21
+ /**
22
+ * The redirect target from an untrusted `next` param when it is a same-origin
23
+ * path, otherwise `fallback` — so a crafted link cannot bounce the user
24
+ * off-site after sign-in.
25
+ *
26
+ * @example safeNext(searchParams.get('next'), '/dashboard')
27
+ * @example safeNext(searchParams.get('next'), null) // null when unsafe
28
+ */
29
+ function safeNext(raw, fallback) {
30
+ return isSafeInternalPath(raw) ? raw : fallback;
31
+ }
32
+ export { isSafeInternalPath, safeNext };
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Route Handler factories: health check and CSP report endpoint.
3
+ */
4
+ /**
5
+ * A CSP violation normalized from either report format. URIs keep only origin
6
+ * and path: query strings and fragments are dropped because they can carry
7
+ * personal data (tokens, emails, search terms). Referrer, script samples and
8
+ * user agent are never kept.
9
+ */
10
+ interface CspViolation {
11
+ /** Page where the violation happened. */
12
+ documentUri: string;
13
+ /** Resource that was blocked: a URL, a scheme such as `data`, or a keyword such as `inline`/`eval`. */
14
+ blockedUri: string;
15
+ /** Directive that was violated, e.g. `script-src-elem`. */
16
+ violatedDirective: string;
17
+ /** `'report'` for report-only policies, `'enforce'` for enforced ones. */
18
+ disposition: 'enforce' | 'report';
19
+ /** Script or stylesheet that triggered the violation, when known. */
20
+ sourceFile?: string;
21
+ lineNumber?: number;
22
+ columnNumber?: number;
23
+ }
24
+ /** Options for {@link cspReportRoute}. */
25
+ interface CspReportRouteOptions {
26
+ /** Receives each violation, e.g. to log it with the app's logger. */
27
+ onReport: (violation: CspViolation) => void | Promise<void>;
28
+ /** Largest accepted body in bytes; larger requests get 413. Defaults to 64 KiB. */
29
+ maxBytes?: number;
30
+ }
31
+ /**
32
+ * A `POST` handler for the CSP report endpoint (`reportPath` of
33
+ * `securityHeaders()`). Accepts `application/csp-report` (`report-uri`) and
34
+ * `application/reports+json` (Reporting API, `report-to`), caps the body size,
35
+ * normalizes each violation with URIs stripped of query and fragment, hands it
36
+ * to `onReport` and answers 204. Errors: 415 wrong content type, 413 too large,
37
+ * 400 invalid JSON.
38
+ *
39
+ * @example export const POST = cspReportRoute({ onReport: (v) => logger.warn(v, 'csp violation') })
40
+ */
41
+ export declare function cspReportRoute(options: CspReportRouteOptions): (request: Request) => Promise<Response>;
42
+ /** Options for {@link healthRoute}. */
43
+ interface HealthRouteOptions {
44
+ /** Resolves when the database answers (e.g. `SELECT 1`); rejects or throws otherwise. */
45
+ ping: () => Promise<unknown>;
46
+ /** How long to wait for `ping` before reporting the database unreachable. Defaults to 4000 ms. */
47
+ timeoutMs?: number;
48
+ /** Receives the ping failure (rejection, throw or timeout), e.g. to log it. */
49
+ onError?: (error: unknown) => void;
50
+ }
51
+ /** JSON body served by {@link healthRoute}. */
52
+ interface HealthBody {
53
+ status: 'ok' | 'error';
54
+ commit: string | null;
55
+ database: 'ok' | 'unreachable';
56
+ }
57
+ /**
58
+ * A `GET` handler for `/api/health`: reports the serving commit
59
+ * (`NEXT_PUBLIC_COMMIT_SHA`, else `VERCEL_GIT_COMMIT_SHA`) and whether the
60
+ * database answers — 200 when it does, 503 when it fails or times out. Never
61
+ * cached: it awaits `connection()` (keeps it out of the Cache Components
62
+ * prerender) and sends `Cache-Control: no-store`.
63
+ *
64
+ * @example export const GET = healthRoute({ ping: () => pool.query('SELECT 1') })
65
+ */
66
+ export declare function healthRoute(options: HealthRouteOptions): () => Promise<Response>;
67
+ export type { CspReportRouteOptions, CspViolation, HealthBody, HealthRouteOptions };
@@ -0,0 +1,161 @@
1
+ import { connection } from "next/server.js";
2
+ // src/server/csp-report.ts
3
+ const ACCEPTED_TYPES = /* @__PURE__ */ new Set([
4
+ "application/csp-report",
5
+ "application/reports+json",
6
+ "application/json"
7
+ ]);
8
+ function isRecord(value) {
9
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10
+ }
11
+ function readString(record, ...keys) {
12
+ for (const key of keys) {
13
+ const value = record[key];
14
+ if (typeof value === "string" && value !== "") return value;
15
+ }
16
+ }
17
+ function readNumber(record, ...keys) {
18
+ for (const key of keys) {
19
+ const value = record[key];
20
+ if (typeof value === "number" && Number.isFinite(value)) return value;
21
+ }
22
+ }
23
+ const WEB_SCHEMES = /* @__PURE__ */ new Set([
24
+ "http:",
25
+ "https:",
26
+ "ws:",
27
+ "wss:"
28
+ ]);
29
+ /**
30
+ * Drop query string and fragment. Web URLs keep origin + path; other URLs
31
+ * (`data:`, `blob:`, extensions) keep only their scheme; keywords pass through.
32
+ */
33
+ function stripUri(uri) {
34
+ if (URL.canParse(uri)) {
35
+ const url = new URL(uri);
36
+ return WEB_SCHEMES.has(url.protocol) ? `${url.origin}${url.pathname}` : url.protocol.slice(0, -1);
37
+ }
38
+ return uri.replace(/[?#].*$/s, "");
39
+ }
40
+ function normalize(raw) {
41
+ const documentUri = readString(raw, "documentURL", "document-uri");
42
+ const violatedDirective = readString(raw, "effectiveDirective", "effective-directive", "violated-directive");
43
+ if (documentUri === void 0 || violatedDirective === void 0) return void 0;
44
+ const sourceFile = readString(raw, "sourceFile", "source-file");
45
+ const lineNumber = readNumber(raw, "lineNumber", "line-number");
46
+ const columnNumber = readNumber(raw, "columnNumber", "column-number");
47
+ return {
48
+ documentUri: stripUri(documentUri),
49
+ blockedUri: stripUri(readString(raw, "blockedURL", "blocked-uri") ?? "inline"),
50
+ violatedDirective,
51
+ disposition: readString(raw, "disposition") === "enforce" ? "enforce" : "report",
52
+ ...sourceFile === void 0 ? {} : { sourceFile: stripUri(sourceFile) },
53
+ ...lineNumber === void 0 ? {} : { lineNumber },
54
+ ...columnNumber === void 0 ? {} : { columnNumber }
55
+ };
56
+ }
57
+ /** Extract violations from a `report-uri` (`{ "csp-report": … }`) or Reporting API (`[{ type, body }]`) payload. */
58
+ function parseCspReports(payload) {
59
+ return (Array.isArray(payload) ? payload.flatMap((report) => isRecord(report) && report.type === "csp-violation" ? [report.body] : []) : [isRecord(payload) ? payload["csp-report"] : void 0]).flatMap((body) => {
60
+ const violation = isRecord(body) ? normalize(body) : void 0;
61
+ return violation === void 0 ? [] : [violation];
62
+ });
63
+ }
64
+ async function readCapped(request, maxBytes) {
65
+ const reader = request.body?.getReader();
66
+ if (reader === void 0) return "";
67
+ const decoder = new TextDecoder();
68
+ let text = "";
69
+ let size = 0;
70
+ for (;;) {
71
+ const { done, value } = await reader.read();
72
+ if (done) break;
73
+ size += value.byteLength;
74
+ if (size > maxBytes) {
75
+ await reader.cancel();
76
+ return;
77
+ }
78
+ text += decoder.decode(value, { stream: true });
79
+ }
80
+ return text + decoder.decode();
81
+ }
82
+ function status(code) {
83
+ return new Response(null, { status: code });
84
+ }
85
+ /**
86
+ * A `POST` handler for the CSP report endpoint (`reportPath` of
87
+ * `securityHeaders()`). Accepts `application/csp-report` (`report-uri`) and
88
+ * `application/reports+json` (Reporting API, `report-to`), caps the body size,
89
+ * normalizes each violation with URIs stripped of query and fragment, hands it
90
+ * to `onReport` and answers 204. Errors: 415 wrong content type, 413 too large,
91
+ * 400 invalid JSON.
92
+ *
93
+ * @example export const POST = cspReportRoute({ onReport: (v) => logger.warn(v, 'csp violation') })
94
+ */
95
+ function cspReportRoute(options) {
96
+ const { onReport, maxBytes = 65536 } = options;
97
+ return async function POST(request) {
98
+ const contentType = (request.headers.get("content-type") ?? "").replace(/;.*$/s, "").trim().toLowerCase();
99
+ if (!ACCEPTED_TYPES.has(contentType)) return status(415);
100
+ if (Number(request.headers.get("content-length") ?? 0) > maxBytes) return status(413);
101
+ const text = await readCapped(request, maxBytes);
102
+ if (text === void 0) return status(413);
103
+ let payload;
104
+ try {
105
+ payload = JSON.parse(text);
106
+ } catch {
107
+ return status(400);
108
+ }
109
+ for (const violation of parseCspReports(payload)) await onReport(violation);
110
+ return status(204);
111
+ };
112
+ }
113
+ // src/server/health.ts
114
+ async function pingWithin(ping, timeoutMs) {
115
+ let timer;
116
+ const timeout = new Promise((_, reject) => {
117
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Ping timed out after ${timeoutMs}ms`)), timeoutMs);
118
+ });
119
+ try {
120
+ await Promise.race([Promise.resolve().then(ping), timeout]);
121
+ } finally {
122
+ clearTimeout(timer);
123
+ }
124
+ }
125
+ /**
126
+ * A `GET` handler for `/api/health`: reports the serving commit
127
+ * (`NEXT_PUBLIC_COMMIT_SHA`, else `VERCEL_GIT_COMMIT_SHA`) and whether the
128
+ * database answers — 200 when it does, 503 when it fails or times out. Never
129
+ * cached: it awaits `connection()` (keeps it out of the Cache Components
130
+ * prerender) and sends `Cache-Control: no-store`.
131
+ *
132
+ * @example export const GET = healthRoute({ ping: () => pool.query('SELECT 1') })
133
+ */
134
+ function healthRoute(options) {
135
+ const { ping, timeoutMs = 4e3, onError } = options;
136
+ return async function GET() {
137
+ await connection();
138
+ const commit = process.env.NEXT_PUBLIC_COMMIT_SHA || process.env.VERCEL_GIT_COMMIT_SHA || null;
139
+ let reachable = true;
140
+ try {
141
+ await pingWithin(ping, timeoutMs);
142
+ } catch (error) {
143
+ reachable = false;
144
+ onError?.(error);
145
+ }
146
+ const body = reachable ? {
147
+ status: "ok",
148
+ commit,
149
+ database: "ok"
150
+ } : {
151
+ status: "error",
152
+ commit,
153
+ database: "unreachable"
154
+ };
155
+ return Response.json(body, {
156
+ status: reachable ? 200 : 503,
157
+ headers: { "Cache-Control": "no-store" }
158
+ });
159
+ };
160
+ }
161
+ export { cspReportRoute, healthRoute };
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@cbrl/next",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Next.js 16 building blocks: security headers with a reporting CSP, commit SHA, dev origins, health and CSP-report route handlers, safeNext.",
5
+ "license": "MIT",
6
+ "author": "Kayron Cabral",
7
+ "homepage": "https://github.com/kaycabral/toolkit/tree/main/packages/next#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/kaycabral/toolkit/issues"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/kaycabral/toolkit.git",
14
+ "directory": "packages/next"
15
+ },
16
+ "keywords": [
17
+ "next",
18
+ "nextjs",
19
+ "csp",
20
+ "security-headers",
21
+ "health-check"
22
+ ],
23
+ "type": "module",
24
+ "sideEffects": false,
25
+ "exports": {
26
+ ".": "./dist/index.mjs",
27
+ "./config": "./dist/config.mjs",
28
+ "./server": "./dist/server.mjs",
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "peerDependencies": {
35
+ "next": "^16.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@arethetypeswrong/cli": "^0.18.5",
39
+ "@types/node": "^25.6.2",
40
+ "@vitest/coverage-v8": "^4.1.6",
41
+ "eslint": "^9.39.4",
42
+ "next": "^16.4.6",
43
+ "publint": "^0.3.25",
44
+ "react": "^19.2.6",
45
+ "react-dom": "^19.2.6",
46
+ "tsdown": "^0.23.7",
47
+ "typescript": "^5.9.3",
48
+ "vitest": "^4.1.6",
49
+ "@cbrl/tsconfig": "0.1.0",
50
+ "@cbrl/testing": "0.2.0",
51
+ "@cbrl/eslint-config": "0.2.0"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "scripts": {
57
+ "build": "tsdown",
58
+ "typecheck": "tsc --noEmit",
59
+ "test": "vitest run --coverage",
60
+ "check:package": "node ../../scripts/check-package.mjs --types",
61
+ "lint": "eslint ."
62
+ }
6
63
  }