@klnap/next-proxy-chain 1.2.0 → 3.0.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/CHANGELOG.md +18 -0
- package/README.md +277 -219
- package/dist/index.cjs +513 -440
- package/dist/index.d.cts +96 -189
- package/dist/index.d.ts +96 -189
- package/dist/index.js +512 -431
- package/docs/api.md +190 -0
- package/docs/concepts.md +88 -0
- package/docs/guides.md +210 -0
- package/docs/security.md +104 -0
- package/llms.txt +17 -0
- package/package.json +19 -18
package/docs/api.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# API reference
|
|
2
|
+
|
|
3
|
+
The runtime entry exports two functions:
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { chain, defineHandler } from "@klnap/next-proxy-chain";
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Next.js owns HTTP responses. Use `NextResponse` from `next/server` and standard Web `Response`, `Headers`, and `AbortSignal`.
|
|
10
|
+
|
|
11
|
+
## `chain()`
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
chain<TContext extends object = object>(
|
|
15
|
+
entries: readonly ChainEntry<TContext>[],
|
|
16
|
+
options?: ChainOptions<TContext>,
|
|
17
|
+
): (request: NextRequest, event: NextFetchEvent) => Promise<NextResponse | Response>
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`chain()` accepts native handler functions and configured handler objects. Entries run sequentially. A `NextResponse.next()` or `undefined` continues; redirects and terminal responses stop.
|
|
21
|
+
|
|
22
|
+
## `defineHandler()`
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
defineHandler<TContext extends object = object>(
|
|
26
|
+
options: HandlerConfig<TContext>,
|
|
27
|
+
): HandlerConfig<TContext>
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
It validates and returns the same configuration object. Inline and reusable configurations have the same type and normalization behavior.
|
|
31
|
+
|
|
32
|
+
## Configured handler
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
type HandlerConfig<TContext extends object = object> = {
|
|
36
|
+
name: string;
|
|
37
|
+
rules?: {
|
|
38
|
+
include?: RouteScopeList;
|
|
39
|
+
exclude?: RouteScopeList;
|
|
40
|
+
when?: HandlerWhen<TContext>;
|
|
41
|
+
};
|
|
42
|
+
timeout?: number;
|
|
43
|
+
debug?: DebugLevel;
|
|
44
|
+
onError?: OnErrorHandler<TContext>;
|
|
45
|
+
handle: NativeProxy<TContext>;
|
|
46
|
+
};
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`name` must be a non-empty string. `handle` must be a function. `rules`, `timeout`, `debug`, and `onError` are optional. `handle` appears last in examples by convention, not requirement.
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
defineHandler({
|
|
53
|
+
name: "authentication",
|
|
54
|
+
rules: { include: "/dashboard/**" },
|
|
55
|
+
timeout: 500,
|
|
56
|
+
debug: true,
|
|
57
|
+
onError: handleError,
|
|
58
|
+
handle: async (request, event, context) => {
|
|
59
|
+
return authenticate(request, event, context.signal);
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Arrow functions are the primary convention for `handle`, `when`, and `onError`. Async functions, function references, and object method syntax also satisfy the contract.
|
|
65
|
+
|
|
66
|
+
## Native handler
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
type NativeProxy<TContext extends object = object> = (
|
|
70
|
+
request: NextRequest,
|
|
71
|
+
event: NextFetchEvent,
|
|
72
|
+
context: HandlerContext<TContext>,
|
|
73
|
+
) =>
|
|
74
|
+
| NextResponse
|
|
75
|
+
| Response
|
|
76
|
+
| undefined
|
|
77
|
+
| void
|
|
78
|
+
| Promise<NextResponse | Response | undefined | void>;
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Two-argument Next.js handlers remain composable. The chain adds context as the optional third callback argument and passes through the original `event`.
|
|
82
|
+
|
|
83
|
+
## Matching
|
|
84
|
+
|
|
85
|
+
`Next.js config.matcher` filters whether the entrypoint runs. Handler `rules` filter configured handlers after entrypoint invocation.
|
|
86
|
+
|
|
87
|
+
- `include` and `exclude` accept a path string, `RegExp`, or objects with `path` and/or `host`.
|
|
88
|
+
- `*` matches one path segment. `**` matches zero or more segments.
|
|
89
|
+
- `exclude` takes precedence over `include`.
|
|
90
|
+
- `when(request, event, context)` may return a boolean or `Promise<boolean>`.
|
|
91
|
+
- Matching uses the effective request at each handler's turn. A continued rewrite changes later path matching and the query visible to predicates; original context metadata remains unchanged.
|
|
92
|
+
- Rewrites do not change the host used for matching. Host scopes read the effective `host` header, falling back to `x-forwarded-host`; a prior native request-header replacement of either header changes later host matching.
|
|
93
|
+
|
|
94
|
+
Host matcher strings compare case-insensitively and ignore ports. Host wildcards match one DNS label. See [Concepts](concepts.md#matching) for examples.
|
|
95
|
+
|
|
96
|
+
## Return values
|
|
97
|
+
|
|
98
|
+
| Handler returns | Chain behavior |
|
|
99
|
+
| ---------------------------- | ------------------------------------------------- |
|
|
100
|
+
| `undefined` | Continue to the next handler. |
|
|
101
|
+
| `NextResponse.next()` | Compose HTTP effects and continue. |
|
|
102
|
+
| `NextResponse.rewrite(url)` | Stage the rewrite and continue to later handlers. |
|
|
103
|
+
| `NextResponse.redirect(url)` | Stop and redirect. |
|
|
104
|
+
| Terminal `Response` | Stop and return the response. |
|
|
105
|
+
|
|
106
|
+
Only `NextResponse` routing responses are interpreted as continuation or rewrite instructions. A plain `Response` remains terminal, even if it contains Next.js routing headers.
|
|
107
|
+
|
|
108
|
+
`NextResponse.rewrite()` continues only for a successful rewrite response. Non-success responses are terminal. Redirects are terminal.
|
|
109
|
+
|
|
110
|
+
## Request headers
|
|
111
|
+
|
|
112
|
+
Use native `NextResponse.next({ request: { headers } })`. Next.js treats `headers` as the replacement request-header set, not a partial merge. Clone the effective request headers to preserve them:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
const headers = new Headers(request.headers);
|
|
116
|
+
headers.set("x-request-id", context.requestId);
|
|
117
|
+
return NextResponse.next({ request: { headers } });
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Removing a header means deleting it from the `Headers` instance before returning it. A replacement that omits a prior request header deletes that header downstream.
|
|
121
|
+
|
|
122
|
+
Each continued native override becomes the effective request seen by later rules. The engine reconstructs `NextRequest` using Next.js's encoded override metadata, while retaining staged rewrite URL state, request signal, and original chain metadata. Request headers remain separate from client-facing response headers.
|
|
123
|
+
|
|
124
|
+
There is no package-level request-header allow/deny policy. Handler code explicitly chooses the forwarded header set. Validate untrusted values before adding or changing headers.
|
|
125
|
+
|
|
126
|
+
## Response headers and cookies
|
|
127
|
+
|
|
128
|
+
Mutate the native response:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
const response = NextResponse.next();
|
|
132
|
+
response.headers.set("x-content-type-options", "nosniff");
|
|
133
|
+
response.cookies.set("locale", "en");
|
|
134
|
+
return response;
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Continued response headers and cookies compose onto the final response. The default merge strategy is last-write-wins. `headerMergeStrategy` and `cookieMergeStrategy` can select `"first-write-wins"` or a custom resolver; returning `null` from a resolver removes that header or cookie identity.
|
|
138
|
+
|
|
139
|
+
Cookie identity includes cookie name, domain, and path. Distinct paths remain distinct.
|
|
140
|
+
|
|
141
|
+
## Context and cancellation
|
|
142
|
+
|
|
143
|
+
`HandlerContext<TContext>` contains:
|
|
144
|
+
|
|
145
|
+
- `requestId`: generated `req_` identifier.
|
|
146
|
+
- `startedAt`: request start time.
|
|
147
|
+
- `elapsedMs`: elapsed request duration.
|
|
148
|
+
- `originalUrl`, `originalPathname`, and `originalHostname`: original request metadata.
|
|
149
|
+
- `signal`: execution-scoped `AbortSignal`.
|
|
150
|
+
- Custom properties from `TContext`.
|
|
151
|
+
|
|
152
|
+
Custom state is shared between handlers for one request and isolated across requests. Properties may be `undefined` until initialized. Context and request IDs are not forwarded to route handlers automatically.
|
|
153
|
+
|
|
154
|
+
## Errors and timeouts
|
|
155
|
+
|
|
156
|
+
`timeout` is a per-handler execution budget in milliseconds; `0` disables timeouts. A handler's timeout overrides the chain timeout. The handler's predicate shares its budget. Timeout aborts the execution signal and stops the chain.
|
|
157
|
+
|
|
158
|
+
Handler-level `onError` takes precedence over chain-level `onError`. For ordinary errors, returning `NextResponse.next()` or a successful `NextResponse.rewrite()` continues after the failed handler; a rewrite is staged like a normal rewrite. Returning any other `Response` terminates with that response. Returning `undefined`, `void`, or `null`, throwing, or returning an unsupported value fails closed.
|
|
159
|
+
|
|
160
|
+
For timeout, request cancellation, and engine-level failures, recovery accepts only a terminal Web `Response`, including a redirect. `NextResponse.next()` and successful `NextResponse.rewrite()` are rejected because they would resume routing. A rejected timeout or engine-level recovery returns `500`. Without recovery, timeout returns `500`. Cancellation stops the package chain and returns a native `NextResponse.next()` handoff; Next.js may continue downstream routing, so this is not a fail-closed response. Error diagnostics record the chosen recovery policy.
|
|
161
|
+
|
|
162
|
+
## Chain options
|
|
163
|
+
|
|
164
|
+
| Option | Default | Meaning |
|
|
165
|
+
| --------------------- | ------------------- | --------------------------------------------------------------------------------------------------- |
|
|
166
|
+
| `timeout` | `0` | Per-handler deadline in milliseconds. |
|
|
167
|
+
| `debug` | `false` | Disable logs, or select `true`, `"compact"`, `"detailed"`, or `"verbose"`. |
|
|
168
|
+
| `logger` | Console logger | Logger with `debug`, `info`, `warn`, and `error` methods. |
|
|
169
|
+
| `onError` | None | Chain-level error recovery. Handler-level `onError` takes precedence. |
|
|
170
|
+
| `onTrace` | None | Receives structured request traces. |
|
|
171
|
+
| `tracePath` | `true` | Include the original request pathname in the top-level structured trace and formatted request line. |
|
|
172
|
+
| `headerMergeStrategy` | `"last-write-wins"` | Resolve response-header conflicts. |
|
|
173
|
+
| `cookieMergeStrategy` | `"last-write-wins"` | Resolve cookie conflicts. |
|
|
174
|
+
| `strictOverrideCheck` | `false` | Throw at chain creation if native Next.js request-header override metadata cannot be verified. |
|
|
175
|
+
|
|
176
|
+
Handler `timeout` and `debug` override their chain-level values. Chain-level `onError` is used only when a handler does not define its own.
|
|
177
|
+
|
|
178
|
+
`strictOverrideCheck` tests whether the active Next.js `NextResponse.next()` encodes a sentinel request-header override. The probe runs when the first chain is constructed and caches its result for that package module. A successful probe is silent and leaves normal native header replacement behavior unchanged.
|
|
179
|
+
|
|
180
|
+
If the probe reports unsupported behavior or throws, `strictOverrideCheck: true` throws during chain construction. With the default `false`, an uncached failed probe warns and chain construction continues; later chains reuse the result without probing again. The package does not emulate the override mechanism. Request-header replacements may then be missing from later handlers or downstream Next.js code. Use `true` to fail fast when the application depends on native request-header forwarding.
|
|
181
|
+
|
|
182
|
+
The probe checks Next.js's generated override metadata. It does not verify that the deployed runtime later applies that metadata.
|
|
183
|
+
|
|
184
|
+
`tracePath: false` removes only the original request pathname from `ChainTrace.pathname` and the formatted request line. It does not remove paths in matched scope details or rewrite and redirect destinations. Destination query values are replaced with `?[query]`.
|
|
185
|
+
|
|
186
|
+
## Public types
|
|
187
|
+
|
|
188
|
+
The package exports `ChainEntry`, `ChainOptions`, `HandlerConfig`, `NativeProxy`, `OnErrorHandler`, `OnErrorResult`, `HandlerContext`, `RequestMetadata`, matcher types, and structured diagnostic types.
|
|
189
|
+
|
|
190
|
+
It exports no helper-specific continuation token, response wrapper, or request-header policy.
|
package/docs/concepts.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Concepts
|
|
2
|
+
|
|
3
|
+
`chain()` composes native handlers. `defineHandler()` defines a reusable configured handler. `handle` contains the handler's native Next.js logic; Next.js owns HTTP responses.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { chain } from "@klnap/next-proxy-chain";
|
|
7
|
+
import { NextResponse } from "next/server";
|
|
8
|
+
|
|
9
|
+
export default chain([
|
|
10
|
+
(request, event) => {
|
|
11
|
+
event.waitUntil(writeAuditLog(request));
|
|
12
|
+
if (request.nextUrl.pathname === "/") {
|
|
13
|
+
return NextResponse.redirect(new URL("/home", request.url));
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: "security",
|
|
18
|
+
handle: () => {
|
|
19
|
+
const response = NextResponse.next();
|
|
20
|
+
response.headers.set("x-content-type-options", "nosniff");
|
|
21
|
+
return response;
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
]);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Execution
|
|
28
|
+
|
|
29
|
+
Handlers execute in order. A `NextResponse.next()` or `undefined` continues. A successful `NextResponse.rewrite()` stages a rewrite and continues. A redirect or terminal `Response` stops the chain. If every handler continues, the chain returns a pass-through response or the final staged rewrite.
|
|
30
|
+
|
|
31
|
+
The original request object is not mutated. When a continued rewrite or native request-header override changes request state, later handlers receive a reconstructed `NextRequest`. Original URL, path, and hostname remain in chain context.
|
|
32
|
+
|
|
33
|
+
## Matching
|
|
34
|
+
|
|
35
|
+
Next.js `config.matcher` is the outer filter. It decides whether Middleware or Proxy runs at all.
|
|
36
|
+
|
|
37
|
+
Configured-handler `rules.include` and `rules.exclude` are inner filters. They accept paths, host/path objects, strings, and regular expressions. Exclusions take precedence. The optional async `when(request, event, context)` predicate runs after scope matching.
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
{
|
|
41
|
+
name: "admin-auth",
|
|
42
|
+
rules: {
|
|
43
|
+
include: { host: "admin.example.com", path: "/admin/**" },
|
|
44
|
+
exclude: "/admin/login",
|
|
45
|
+
},
|
|
46
|
+
handle: (request) => {
|
|
47
|
+
if (!hasSession(request)) {
|
|
48
|
+
return NextResponse.redirect(new URL("/login", request.url));
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Later matching uses the effective request, including prior rewrite paths and request-header replacements. Rewrites do not change the host used for matching; host scopes read the effective `host` header, falling back to `x-forwarded-host`. A prior header replacement of either value affects later host matching.
|
|
55
|
+
|
|
56
|
+
## Native HTTP composition
|
|
57
|
+
|
|
58
|
+
The chain does not wrap responses in another API. Handlers return `NextResponse` or Web `Response` directly.
|
|
59
|
+
|
|
60
|
+
| Handler returns | Effect |
|
|
61
|
+
| ---------------------------- | ------------------------------------------------------ |
|
|
62
|
+
| `undefined` | Continue without adding HTTP effects. |
|
|
63
|
+
| `NextResponse.next()` | Continue and compose its response headers and cookies. |
|
|
64
|
+
| `NextResponse.rewrite(url)` | Stage the rewrite; continue through later handlers. |
|
|
65
|
+
| `NextResponse.redirect(url)` | Stop and redirect. |
|
|
66
|
+
| Terminal `Response` | Stop and return it. |
|
|
67
|
+
|
|
68
|
+
Request headers passed in `NextResponse.next({ request: { headers } })` replace the forwarded request-header set. Clone `request.headers` to preserve existing values. The engine decodes Next.js's internal override metadata so later handlers see the same effective headers. Request headers do not become response headers.
|
|
69
|
+
|
|
70
|
+
Response headers and cookies from continuing handlers are collected and merged into the final response. The defaults use last-write-wins. Cookies with different name/domain/path identities remain distinct.
|
|
71
|
+
|
|
72
|
+
## Context
|
|
73
|
+
|
|
74
|
+
The chain creates request-scoped metadata and an execution-scoped `AbortSignal`. `requestId`, `startedAt`, `elapsedMs`, `originalUrl`, `originalPathname`, and `originalHostname` describe the original request. Custom typed state is shared between handlers in one request and isolated across requests.
|
|
75
|
+
|
|
76
|
+
Custom state fields may be `undefined` before initialization. They are not forwarded to route handlers unless a handler explicitly encodes them into request headers.
|
|
77
|
+
|
|
78
|
+
## Errors and timeouts
|
|
79
|
+
|
|
80
|
+
The handler's `timeout` and `when` predicate share a deadline. Timeout or request cancellation aborts the execution signal and stops the pipeline from waiting; ignored work can continue. A cooperative handler should pass `context.signal` to cancellable work.
|
|
81
|
+
|
|
82
|
+
For ordinary errors, handler-level `onError` wins over chain-level `onError`. `NextResponse.next()` and a successful `NextResponse.rewrite()` continue after that failed handler; any other `Response` terminates. Timeouts, request cancellation, and engine-level failures cannot resume the chain. They accept only a terminal Web `Response` as recovery; a continuing or rewriting recovery is rejected.
|
|
83
|
+
|
|
84
|
+
## Diagnostics
|
|
85
|
+
|
|
86
|
+
Formatted diagnostics include one outcome per handler. Compact `reached/total` counts include skipped outcomes, because their scope or predicate was evaluated; handlers after a terminal response count only in `total`.
|
|
87
|
+
|
|
88
|
+
`onTrace` receives structured data with request ID, outcome, timing, and handler details. `tracePath: false` omits the original request pathname from the top-level trace and formatted request line; scope details and sanitized rewrite or redirect destination paths remain visible. Destination query values are replaced with `?[query]`. The formatter sanitizes and truncates displayed names and destinations.
|
package/docs/guides.md
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
# Guides
|
|
2
|
+
|
|
3
|
+
## Native matcher configuration
|
|
4
|
+
|
|
5
|
+
Keep the Next.js matcher at the entrypoint. Use `rules` to scope one handler:
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
export const config = { matcher: ["/api/:path*"] };
|
|
9
|
+
|
|
10
|
+
export default chain([
|
|
11
|
+
{
|
|
12
|
+
name: "api-auth",
|
|
13
|
+
rules: {
|
|
14
|
+
include: "/api/**",
|
|
15
|
+
exclude: "/api/public/**",
|
|
16
|
+
when: async (request) => request.headers.has("authorization"),
|
|
17
|
+
},
|
|
18
|
+
handle: (request) => verifyApiRequest(request),
|
|
19
|
+
},
|
|
20
|
+
]);
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Path strings support `*` for one segment and `**` for zero or more segments. Scope objects can combine `host` and `path`.
|
|
24
|
+
|
|
25
|
+
## Add, update, and remove request headers
|
|
26
|
+
|
|
27
|
+
Next.js treats the supplied `Headers` as a replacement set. Clone the effective request headers to preserve existing values:
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { NextResponse } from "next/server";
|
|
31
|
+
|
|
32
|
+
{
|
|
33
|
+
name: "request-metadata",
|
|
34
|
+
handle: (request) => {
|
|
35
|
+
const headers = new Headers(request.headers);
|
|
36
|
+
headers.set("x-user-tier", "free");
|
|
37
|
+
headers.set("x-request-source", "proxy");
|
|
38
|
+
headers.delete("x-untrusted-client-value");
|
|
39
|
+
return NextResponse.next({ request: { headers } });
|
|
40
|
+
},
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
To deliberately replace the entire set, create a new `Headers` instance and add only the values to forward. Headers omitted from that set are removed downstream. A later handler sees the effective result and can clone it before making another change.
|
|
45
|
+
|
|
46
|
+
## Forward a request ID
|
|
47
|
+
|
|
48
|
+
The chain generates `context.requestId`, but does not forward it automatically:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import { NextResponse } from "next/server";
|
|
52
|
+
|
|
53
|
+
{
|
|
54
|
+
name: "request-id",
|
|
55
|
+
handle: (request, _event, context) => {
|
|
56
|
+
const headers = new Headers(request.headers);
|
|
57
|
+
headers.set("x-request-id", context.requestId);
|
|
58
|
+
return NextResponse.next({ request: { headers } });
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
This changes request headers seen by downstream handlers and route code. It does not set a client-facing response header.
|
|
64
|
+
|
|
65
|
+
## Set response headers and cookies
|
|
66
|
+
|
|
67
|
+
Use the native response object:
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
import { NextResponse } from "next/server";
|
|
71
|
+
|
|
72
|
+
{
|
|
73
|
+
name: "security",
|
|
74
|
+
handle: () => {
|
|
75
|
+
const response = NextResponse.next();
|
|
76
|
+
response.headers.set("x-content-type-options", "nosniff");
|
|
77
|
+
response.cookies.set("locale", "en");
|
|
78
|
+
return response;
|
|
79
|
+
},
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Response headers and cookies are composed across continued handlers. Last write wins by default.
|
|
84
|
+
|
|
85
|
+
## Rewrite and continue
|
|
86
|
+
|
|
87
|
+
A successful rewrite is staged. Later handlers receive the rewritten pathname, while `context.originalPathname` retains the original value:
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { NextResponse } from "next/server";
|
|
91
|
+
|
|
92
|
+
{
|
|
93
|
+
name: "localized-route",
|
|
94
|
+
rules: { include: "/**" },
|
|
95
|
+
handle: (request) => {
|
|
96
|
+
if (request.nextUrl.pathname.startsWith("/pl/")) return;
|
|
97
|
+
return NextResponse.rewrite(new URL(`/pl${request.nextUrl.pathname}`, request.url));
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Internal and external destinations use Next.js's `NextResponse.rewrite()` API. A later redirect or terminal response stops the chain.
|
|
103
|
+
|
|
104
|
+
## Redirect
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { NextResponse } from "next/server";
|
|
108
|
+
|
|
109
|
+
{
|
|
110
|
+
name: "canonical-host",
|
|
111
|
+
handle: (request) => {
|
|
112
|
+
if (request.nextUrl.hostname !== "www.example.com") {
|
|
113
|
+
return NextResponse.redirect(new URL(request.url.replace("://", "://www."), request.url));
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Redirects are terminal. Earlier composed response headers and cookies remain on the outgoing response.
|
|
120
|
+
|
|
121
|
+
## Share typed context
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
type RequestState = { locale?: "en" | "pl" };
|
|
125
|
+
|
|
126
|
+
export default chain<RequestState>([
|
|
127
|
+
{
|
|
128
|
+
name: "detect-locale",
|
|
129
|
+
handle: (request, _event, context) => {
|
|
130
|
+
context.locale = request.headers.get("accept-language")?.startsWith("pl") ? "pl" : "en";
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
name: "locale-header",
|
|
135
|
+
handle: (_request, _event, context) => {
|
|
136
|
+
if (!context.locale) return;
|
|
137
|
+
const response = NextResponse.next();
|
|
138
|
+
response.headers.set("content-language", context.locale);
|
|
139
|
+
return response;
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
]);
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Custom context properties may be undefined until initialized. The chain isolates custom state between requests.
|
|
146
|
+
|
|
147
|
+
## Timeout and cancellation
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
{
|
|
151
|
+
name: "remote-settings",
|
|
152
|
+
timeout: 500,
|
|
153
|
+
handle: async (_request, _event, context) => {
|
|
154
|
+
return fetchSettings({ signal: context.signal });
|
|
155
|
+
},
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
The handler and its `when` predicate share one timeout. Pass `context.signal` into supported APIs. Timeout stops later handlers; ignored work may continue if it does not honor cancellation.
|
|
160
|
+
|
|
161
|
+
## Error recovery
|
|
162
|
+
|
|
163
|
+
For ordinary failures, return native `NextResponse.next()` to continue:
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
{
|
|
167
|
+
name: "optional-profile",
|
|
168
|
+
onError: () => NextResponse.next(),
|
|
169
|
+
handle: async () => loadOptionalProfile(),
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
For timeout and request cancellation, recovery must return a terminal Web `Response`:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
{
|
|
177
|
+
name: "critical-profile",
|
|
178
|
+
onError: () => new Response("Service unavailable", { status: 503 }),
|
|
179
|
+
timeout: 500,
|
|
180
|
+
handle: async (_request, _event, context) => loadProfile({ signal: context.signal }),
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Handler-level `onError` takes precedence over chain-level `onError`. An absent recovery response fails closed.
|
|
185
|
+
|
|
186
|
+
## Diagnostics
|
|
187
|
+
|
|
188
|
+
Enable readable traces with `debug`:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
export default chain(handlers, { debug: "detailed" });
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Set `debug: "compact"` for a short trace. Compact `reached/total` counts include skipped handlers as reached outcomes, but skipped handlers did not execute their `handle` callback. Handlers after a terminal outcome count only in total.
|
|
195
|
+
|
|
196
|
+
Use `onTrace` for structured data:
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
export default chain(handlers, {
|
|
200
|
+
onTrace: (trace) => {
|
|
201
|
+
console.info({
|
|
202
|
+
requestId: trace.requestId,
|
|
203
|
+
outcome: trace.outcome.type,
|
|
204
|
+
handlers: trace.handlers,
|
|
205
|
+
});
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
`tracePath: false` omits only the original request pathname from the top-level trace and formatted request line. It does not hide paths in scope details or sanitized rewrite and redirect destinations; destination query values appear as `?[query]`. Formatted traces and structured traces omit request and response header values, cookie values, raw query values, request bodies, application context values, and raw errors. Display formatting sanitizes and truncates handler names and destinations.
|
package/docs/security.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# Security
|
|
2
|
+
|
|
3
|
+
`@klnap/next-proxy-chain` organizes code that runs in Proxy or Middleware. It does not decide what is allowed. Your rules decide that. This page separates package guarantees from application responsibilities.
|
|
4
|
+
|
|
5
|
+
## Trust boundaries
|
|
6
|
+
|
|
7
|
+
- **Request data is untrusted.** Paths, queries, cookies, headers, and hosts can be set by clients.
|
|
8
|
+
- **Handlers are trusted code.** A handler can set request headers, response headers, cookies, stop the chain, or rewrite a path.
|
|
9
|
+
- **Upstream responses are data.** Relayed response headers pass through except Next.js routing metadata, which is stripped from terminal responses.
|
|
10
|
+
|
|
11
|
+
## Authentication
|
|
12
|
+
|
|
13
|
+
The package runs your authentication check; it does not perform one. A present cookie does not prove a session. Verify the session or token in trusted server code:
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
const requireSession = defineHandler({
|
|
17
|
+
name: "require-session",
|
|
18
|
+
handle: async (request) => {
|
|
19
|
+
const session = await verifySession(request.cookies.get("session")?.value);
|
|
20
|
+
if (!session) return NextResponse.redirect(new URL("/login", request.url));
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`verifySession` is application-owned. Proxy runs before the route, so route handlers must still authorize access to returned data.
|
|
26
|
+
|
|
27
|
+
Server Functions (Server Actions) use POST requests to their route. Excluding that route from `config.matcher` also skips those calls. Enforce authorization inside each Server Function.
|
|
28
|
+
|
|
29
|
+
## Ordering and early responses
|
|
30
|
+
|
|
31
|
+
A redirect or terminal `Response` stops the chain. Later handlers do not run, so their checks, headers, and cookies are absent.
|
|
32
|
+
|
|
33
|
+
Put universal security headers first. Put authentication before handlers that can answer a request, such as cache or static-response handlers.
|
|
34
|
+
|
|
35
|
+
## Path matching
|
|
36
|
+
|
|
37
|
+
- Scopes match decoded paths without a trailing slash. `/%61dmin/users` is matched as `/admin/users`.
|
|
38
|
+
- `/api/*` matches one segment; `/api/**` matches all descendants.
|
|
39
|
+
- Malformed percent encoding returns `400 Bad Request` before handlers run.
|
|
40
|
+
- A handler sees rewrites staged by earlier handlers. Verify that the path it protects is the path Next.js serves.
|
|
41
|
+
|
|
42
|
+
## Host matching
|
|
43
|
+
|
|
44
|
+
The `host` header comes from the client or a proxy and is not trusted by default. Host scopes are routing aids, not access control. Use a platform host allowlist.
|
|
45
|
+
|
|
46
|
+
- Ports and trailing dots are ignored.
|
|
47
|
+
- Host strings compare case-insensitively. Wildcards match one DNS label.
|
|
48
|
+
- If `host` is missing, matching falls back to `x-forwarded-host`. Trust that header only when a proxy you control sets it.
|
|
49
|
+
|
|
50
|
+
## Request headers
|
|
51
|
+
|
|
52
|
+
`NextResponse.next({ request: { headers } })` uses Next.js's native request-header override mechanism. The supplied `Headers` instance replaces the forwarded header set. Clone `request.headers` to preserve values; omitted values are removed. Later handlers receive the effective replacement.
|
|
53
|
+
|
|
54
|
+
There is no package-level header allowlist or blocklist. Handler code chooses which headers to forward. Validate any client-controlled value before using it for identity, authorization, host routing, or rewrite decisions. A forwarded header is not trusted merely because Proxy set it; clients may reach a route directly.
|
|
55
|
+
|
|
56
|
+
Request overrides remain separate from outgoing response headers. The package reads Next.js's override metadata to reconstruct the request for later handlers. It strips Next.js routing metadata from terminal responses, including error-recovered responses, so transport instructions are not forwarded as ordinary response headers.
|
|
57
|
+
|
|
58
|
+
## Rewrites
|
|
59
|
+
|
|
60
|
+
Handlers may use native `NextResponse.rewrite()` for internal or external destinations. Validate destinations derived from request data. Do not pass an untrusted redirect or rewrite target through without checking its origin and allowed paths.
|
|
61
|
+
|
|
62
|
+
## Response headers and cookies
|
|
63
|
+
|
|
64
|
+
- Headers from continuing handlers merge onto the final response. `last-write-wins` is the default.
|
|
65
|
+
- Cookies use name, domain, and path identity. A later cookie with the same identity replaces an earlier one by default.
|
|
66
|
+
- Next.js routing headers are stripped from terminal responses. Native `NextResponse.next()` and `NextResponse.rewrite()` metadata is interpreted only as routing behavior, not copied to the client as ordinary response headers.
|
|
67
|
+
|
|
68
|
+
## Diagnostics and privacy
|
|
69
|
+
|
|
70
|
+
Debug logs and `onTrace` are disabled unless enabled. Formatted traces and structured traces omit request and response header values, cookie values, request bodies, application context values, and raw errors. Redirect and rewrite query values are redacted.
|
|
71
|
+
|
|
72
|
+
Pathnames can contain personal data. `tracePath: false` omits only the original request pathname from the top-level structured trace and formatted request line. It does not hide paths in handler scope details or sanitized rewrite and redirect destinations. Destination query values appear as `?[query]`. Handler names and scope strings are sanitized and length-limited before display.
|
|
73
|
+
|
|
74
|
+
Treat traces as operational data. Logger callbacks can persist them beyond the request; the package cannot control retention, access, or cross-process ordering.
|
|
75
|
+
|
|
76
|
+
## Error recovery
|
|
77
|
+
|
|
78
|
+
For ordinary handler errors, handler-level `onError` takes precedence over chain-level `onError`:
|
|
79
|
+
|
|
80
|
+
- `NextResponse.next()` and a successful `NextResponse.rewrite()` continue after the failed handler.
|
|
81
|
+
- A Web `Response` terminates with that response.
|
|
82
|
+
- `undefined`, `void`, `null`, a throw, or an unsupported return fails closed with `500`.
|
|
83
|
+
|
|
84
|
+
Timeout, request-cancellation, and engine-level recovery accept only a terminal Web `Response`. Continuation and `NextResponse.rewrite()` are rejected, so a timed-out gate cannot rewrite a request past later handlers. This is routing correctness, not an authorization guarantee: the application remains responsible for its own access checks. Without timeout recovery, the chain returns `500`, but ignored work may continue. Without cancellation recovery, the chain stops and returns the native `NextResponse.next()` handoff; Next.js may continue downstream routing after a client disconnect. This handoff is not fail-closed.
|
|
85
|
+
|
|
86
|
+
## Timeouts
|
|
87
|
+
|
|
88
|
+
Handler `timeout` covers its `when` predicate and `handle` together. Timeout or request cancellation aborts the execution-scoped signal and stops the engine from waiting. Cooperative work can stop early; synchronous JavaScript, ignored signals, and side effects cannot be forcibly stopped or undone.
|
|
89
|
+
|
|
90
|
+
Each handler execution gets its own signal. The predicate shares that handler's signal. `event.waitUntil()` work is not supervised by the timeout; pass `context.signal` explicitly when background work should follow the handler lifetime.
|
|
91
|
+
|
|
92
|
+
## Context
|
|
93
|
+
|
|
94
|
+
Each request gets isolated context. Built-in request metadata is immutable; application properties are mutable. `originalUrl` may contain sensitive query values. Do not log or forward it without redaction. Context values do not enter built-in diagnostics.
|
|
95
|
+
|
|
96
|
+
## Next.js version notes
|
|
97
|
+
|
|
98
|
+
- Next.js 16 uses `proxy.ts` and the Node.js runtime by default. Proxy does not accept a `runtime` setting.
|
|
99
|
+
- Next.js 15 uses `middleware.ts` and may run on Edge. Edge behavior must be verified separately for the target release.
|
|
100
|
+
- `config.matcher` decides which paths reach Proxy or Middleware. Handler scopes cannot widen that set.
|
|
101
|
+
|
|
102
|
+
## Reporting a vulnerability
|
|
103
|
+
|
|
104
|
+
Do not open a public issue for a security problem. Use GitHub's private vulnerability reporting from the repository's **Security** tab.
|
package/llms.txt
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# @klnap/next-proxy-chain
|
|
2
|
+
|
|
3
|
+
> Composable proxy and middleware for Next.js.
|
|
4
|
+
|
|
5
|
+
Handler callbacks are positional: use `request`, `event`, and `context` for used parameters; prefix intentionally unused parameters with `_` when later arguments need their positions, and omit unused trailing parameters.
|
|
6
|
+
|
|
7
|
+
The only runtime exports are `chain()` and `defineHandler()`. Configured handlers use `handle`, not `handler`. `undefined` and `NextResponse.next()` continue; successful `NextResponse.rewrite()` stages a rewrite and continues; redirects and terminal `Response` values stop the chain. Use native Next.js and Web response APIs.
|
|
8
|
+
|
|
9
|
+
## Documentation
|
|
10
|
+
|
|
11
|
+
- [README](README.md): purpose, quick start, canonical usage, compatibility, and documentation discovery.
|
|
12
|
+
- [Concepts](docs/concepts.md): execution order, matching, rewrites, HTTP effects, context, and timeouts.
|
|
13
|
+
- [Guides](docs/guides.md): native matchers, practical handler recipes, request IDs, cancellation, and diagnostics.
|
|
14
|
+
- [API reference](docs/api.md): exports, handler configuration, matching syntax, options, types, and defaults.
|
|
15
|
+
- [Security](docs/security.md): trust boundaries, native request-header replacement, authorization, rewrites, and diagnostics privacy.
|
|
16
|
+
|
|
17
|
+
Read the installed README and relevant supporting pages before integrating. The public declarations are in `dist/index.d.ts` and `dist/index.d.cts`.
|