@klnap/next-proxy-chain 1.0.5 → 1.0.7

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 CHANGED
@@ -4,7 +4,44 @@ All notable changes to `@klnap/next-proxy-chain` will be documented in this file
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
5
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
- ## [Unreleased]
7
+ ## [1.0.7] - 2026-11-22
8
+
9
+ ### Fixed
10
+
11
+ - Responses with immutable headers (`Response.redirect()`, `fetch()` responses) are copied before headers are merged. Before, a rule returning them produced a `500` on Node.js.
12
+ - A fail-closed `500` keeps the headers and cookies that earlier rules set, such as a CSP header.
13
+ - Request overrides go to Next.js only when a rule changed a request header. Before, every request header was encoded as `x-middleware-request-*` on every request.
14
+ - `hostFolderHeader` matches whole path segments: `/tenant-other` is not treated as inside `/tenant`.
15
+ - `strictOverrideCheck` verifies that Next.js applies request overrides, not only the continuation flag.
16
+
17
+ ## [1.0.6] - 2026-11-22
18
+
19
+ ### Fixed
20
+
21
+ - `onError` returning `NextResponse.next()` continues the pipeline at rule level, as `next()` does. Previously it stopped the chain and skipped later rules (including auth) while still returning `next`.
22
+ - Engine-level `onError` responses merge headers and cookies from earlier rules.
23
+ - Scope matching uses the percent-decoded, trailing-slash-free path. `include: path("/admin/**")` no longer misses `/%61dmin/…` or `/admin/`.
24
+ - `**` path scopes match decoded control characters such as `%0A` and `%E2%80%A8`. Before this fix, `/admin/%0Asecret` skipped an auth rule on a live Next.js 16.3.2 app.
25
+ - Malformed percent-encoding returns `400` instead of skipping rules.
26
+ - Regex path patterns keep top-level alternation inside their anchors (`path(/\/public|\/static/)` no longer matches `/admin/static`).
27
+ - A trailing dot in the `Host` header is ignored when matching host scopes.
28
+ - A malformed rule return (for example a string) is reported to `onError` with that rule's index instead of `-1`.
29
+ - Next.js routing headers (`x-middleware-override-headers`, `x-middleware-request-*`) are removed from responses returned by `onError`, as they already were for rule responses.
30
+
31
+ ### Security
32
+
33
+ - Only `NextResponse` can continue the chain or request a rewrite through `x-middleware-next` or `x-middleware-rewrite`. A relayed plain `Response` keeps its body and cannot rewrite the request.
34
+ - Bare object scopes (`{ run, include }` with a RegExp instead of `path()`/`host()`) throw at startup. Before, they matched every request.
35
+ - Path segments that mix a wildcard with other characters (for example `/files/*.pdf`) throw at startup. Before, they matched a literal and silently never ran the rule.
36
+ - `ruleTimeoutMs` rejects negative values. Before, they silently disabled the timeout.
37
+ - CI workflow: read-only `GITHUB_TOKEN` permissions, no persisted checkout credentials, actions pinned to commit SHAs.
38
+
39
+ ### Documentation
40
+
41
+ - README rewritten around adoption: what the package does, when to use it, a quick start that puts the security header first.
42
+ - New `docs/` section: concepts (execution model), guides, API reference, security notes.
43
+ - `examples/` contains type-checked examples, each tested in `tests/docs/`. The admin example no longer gates on cookie presence or host, and the locale rewrite example has a matcher.
44
+ - API notes: `headers` on proxy responses, one-sided RegExp anchors, `-1` error index, `*` and `**` as whole segments, Server Functions and matchers.
8
45
 
9
46
  ## [1.0.5] - 2026-10-29
10
47
 
package/README.md CHANGED
@@ -1,223 +1,87 @@
1
1
  # @klnap/next-proxy-chain
2
2
 
3
- Composable request pipeline for Next.js middleware and proxy.
3
+ Compose independent request rules for Next.js `proxy.ts` (or `middleware.ts`) without writing one long function.
4
4
 
5
- ---
5
+ Next.js gives each app one `proxy` export. Once that file also checks sessions, sets security headers, picks a locale, and redirects old URLs, the order of those checks matters, and each one has to know about the others. This package lets each concern be its own rule. The rules run in order, can be limited to certain paths or hosts, and share request-scoped state without any global variables.
6
6
 
7
- ## Requirements
7
+ ```ts
8
+ import { defineProxy, next, path, proxyChain } from '@klnap/next-proxy-chain'
9
+ import { NextResponse } from 'next/server'
8
10
 
9
- `next` `>=15.0.0` (peer dependency).
11
+ const securityHeaders = defineProxy('security-headers', () =>
12
+ next({ headers: { 'x-frame-options': 'DENY' } })
13
+ )
10
14
 
11
- ---
12
-
13
- ## Features
14
-
15
- - **Linear Composition**: Chain independent rules sequentially into a single Next.js middleware or proxy handler.
16
- - **Next.js 15 & 16**: Supports both `middleware.ts` and `proxy.ts`.
17
- - **Request-Scoped Context**: Isolated per-request context for sharing state between rules without global state.
18
- - **Deterministic Header & Cookie Merging**: Propagate request header overrides downstream, deduplicate `Set-Cookie` headers, and merge response headers with configurable conflict strategies.
19
- - **Route & Host Scoping**: Declarative path matching (globs, parameters, regex) and host filtering with `include` and `exclude` rules.
20
- - **Safe Pattern Matching**: Normalizes stateful regular expressions to avoid `lastIndex`-related matching issues.
21
- - **Explicit Flow Control**: Return `next({ request, headers })` to continue, or a terminal `Response` / `NextResponse.redirect` / `NextResponse.json` to stop. `NextResponse.rewrite` **continues** the pipeline (rewrite is applied at the end unless a later rule stops).
22
- - **Timeouts & Error Recovery**: Optional per-rule timeouts (`ruleTimeoutMs`). `onError` is fail-closed: returning nothing yields 500; return `next()` to continue; return a `Response` to stop.
23
- - **Zero Runtime Dependencies**: Fully typed in TypeScript with no runtime dependencies (`next` is a peer).
24
-
25
- ---
26
-
27
- ## Quick Start
28
-
29
- ```typescript
30
- // proxy.ts or middleware.ts
31
- import { defineProxy, next, path, proxyChain } from "@klnap/next-proxy-chain"
32
- import { NextResponse } from "next/server"
33
-
34
- const auth = defineProxy("auth", (req, ctx) => {
35
- const token = req.cookies.get("session")?.value
36
- if (!token) {
37
- return NextResponse.redirect(new URL("/login", req.url))
15
+ const requireSession = defineProxy('require-session', (req) => {
16
+ if (!req.cookies.has('session')) {
17
+ return NextResponse.redirect(new URL('/login', req.url))
38
18
  }
39
- ctx.set("userId", "usr_123")
40
19
  return next()
41
20
  })
42
21
 
43
- const security = defineProxy("security", () => {
44
- return next({
45
- headers: { "x-frame-options": "DENY" },
46
- })
47
- })
48
-
49
- export default proxyChain({ debug: process.env.NODE_ENV !== "production" }, [
50
- auth({ include: path("/dashboard/*") }),
51
- security,
52
- ])
22
+ export default proxyChain([securityHeaders, requireSession({ include: path('/dashboard/**') })])
53
23
 
54
24
  export const config = {
55
- matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
25
+ matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
56
26
  }
57
27
  ```
58
28
 
59
- ---
29
+ This sets `X-Frame-Options` on every response and sends visitors without a session cookie from `/dashboard` to `/login`. The security header comes first, so it also appears on the redirect.
60
30
 
61
- ## Routing & Scoping
62
-
63
- Scope rules to specific paths, hosts, or combinations using `defineProxy`:
64
-
65
- ```typescript
66
- import { defineProxy, host, next, path } from "@klnap/next-proxy-chain"
67
-
68
- const apiAuth = defineProxy("apiAuth", async (req, ctx) => {
69
- // Executed only for /api/* requests except /api/public/*
70
- return next()
71
- })
72
-
73
- // Scoped rule configuration
74
- const scopedRule = apiAuth({
75
- include: path("/api/*"),
76
- exclude: path("/api/public/*"),
77
- })
31
+ ## Install
78
32
 
79
- // Combined path and host filter
80
- const adminRule = apiAuth({
81
- include: {
82
- host: host("admin.example.com"),
83
- path: path("/settings/**"),
84
- },
85
- })
33
+ ```sh
34
+ npm install @klnap/next-proxy-chain
35
+ # or
36
+ bun add @klnap/next-proxy-chain
86
37
  ```
87
38
 
88
- ### Path Patterns
89
-
90
- - `path("/api/*")` — exactly one segment (`/api/users` yes, `/api/users/123` no)
91
- - `path("/docs/**")` — the prefix plus zero or more extra segments (`/docs`, `/docs/a/b`)
92
- - `path("/users/:id")` — one segment (no capture groups; matching only)
93
- - `path(/^\/foo$/)` — user anchors are kept (`/foo` yes, `/x/foo` no)
39
+ `next` is a peer dependency (`>=15.0.0`). The package has no runtime dependencies.
94
40
 
95
- ### Host Patterns
41
+ ## When to use it
96
42
 
97
- - `host("admin.example.com")` — exact hostname (case-insensitive, port stripped at match time)
98
- - `host("*.example.com")` — one DNS label (`foo.example.com` yes, `example.com` no, `a.b.example.com` no)
99
- - `host(/shop\.localhost$/)` — raw RegExp
43
+ Use it when one Proxy file needs several independent concerns, for example:
100
44
 
101
- ---
45
+ - a session check on some routes and not others,
46
+ - security headers on every response,
47
+ - a locale rewrite,
48
+ - a redirect from old URLs,
49
+ - request IDs passed to route handlers.
102
50
 
103
- ## State & Header Mutation
51
+ A single redirect rule does not need it. Write `NextResponse.redirect` directly in `proxy.ts`.
104
52
 
105
- ### Request Context
53
+ It is a composition layer, not a security product. It does not authenticate users, verify tokens, or replace Next.js routing. It runs the rules you write, in the order you list them.
106
54
 
107
- Default context is an isolated `Map<string, unknown>` per request. For a typed object, pass `createContext` — TypeScript then follows the factory, not a fake generic:
55
+ ## How it works
108
56
 
109
- ```typescript
110
- type Ctx = { user?: { id: string; role: string } }
111
-
112
- const enrichUser = defineProxy<Ctx>("enrichUser", async (req, ctx) => {
113
- ctx.user = { id: "usr_1", role: "admin" }
114
- return next()
115
- })
116
-
117
- const checkPermission = defineProxy<Ctx>("checkPermission", (req, ctx) => {
118
- if (ctx.user?.role !== "admin") {
119
- return new Response("Forbidden", { status: 403 })
120
- }
121
- return next()
122
- })
57
+ - Rules run in array order. A rule continues by returning `next()` or nothing, and stops the chain by returning a `Response`.
58
+ - A rule can be scoped with `include` and `exclude` paths or hosts. Rules that do not match are skipped.
59
+ - Headers and cookies set by earlier rules are kept on the final response, unless a later rule overrides them.
60
+ - Each request gets its own context. Rules can share values through it without globals.
61
+ - Errors and timeouts can be recovered with `onError`. By default they produce a 500.
123
62
 
124
- export default proxyChain({ createContext: (): Ctx => ({}) }, [enrichUser, checkPermission])
125
- ```
63
+ [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md) explains the execution model in full.
126
64
 
127
- Without `createContext`, `ctx` is `ProxyContext` (`Map`). Do not write `proxyChain<{ user: string }>(rules)` — that is a type error.
65
+ ## Documentation
128
66
 
129
- ### Request and Response Headers
67
+ - [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md): rule order, continuation, scoping, headers, cookies, errors.
68
+ - [Guides](https://github.com/klnap/next-proxy-chain/blob/main/docs/guides.md): recipes for common tasks, with links to runnable examples.
69
+ - [API reference](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md): every export and option.
70
+ - [Security](https://github.com/klnap/next-proxy-chain/blob/main/docs/security.md): trust boundaries and safe usage.
130
71
 
131
- Use `next()` to inject **request** headers (visible to downstream rules and route handlers) and **response** headers (including `Set-Cookie`):
72
+ Runnable examples live in [`examples/`](https://github.com/klnap/next-proxy-chain/blob/main/examples/). They are type-checked and tested in this repository.
132
73
 
133
- ```typescript
134
- return next({
135
- // Downstream request headers (NextRequest & server components). Always last-write-wins.
136
- request: {
137
- "x-user-id": "usr_123",
138
- },
139
- // Final outgoing response headers / Set-Cookie
140
- headers: {
141
- "cache-control": "no-store",
142
- "set-cookie": "session=abc; Path=/",
143
- },
144
- })
145
- ```
74
+ ## Compatibility
146
75
 
147
- - `headerMergeStrategy` / `cookieMergeStrategy` apply to **response** headers and cookies only.
148
- - Request overrides ignore those strategies (last write wins).
149
- - Cookies are keyed by **name + domain + path**, so `session; Path=/` and `session; Path=/admin` both survive.
150
- - Custom merge `return null` removes that response header from the final `Response`.
151
-
152
- ---
153
-
154
- ## API Reference
155
-
156
- ### Core Functions
157
-
158
- | Function | Signature | Description |
159
- | :--- | :--- | :--- |
160
- | `proxyChain(rules)` | `(rules: Entry[]) => Handler` | Creates a middleware/proxy handler from a list of rules. |
161
- | `proxyChain(options, rules)` | `(options: ProxyChainOptions, rules: Entry[]) => Handler` | Creates a handler with custom pipeline options. |
162
- | `defineProxy(name?, fn)` | `(name?: string, fn: ProxyFn) => DefinedProxy` | Defines a reusable proxy rule with scoping capabilities. |
163
- | `next(options?)` | `(options?: NextOptions) => NextResult` | Returns a continuation token with optional header mutations. |
164
- | `path(pattern)` | `(pattern: string \| RegExp) => RegExp` | Compiles a path pattern into a stateless `RegExp`. |
165
- | `host(matcher)` | `(matcher: HostMatcher) => RegExp` | Compiles hostname(s) into an anchored `RegExp` (`*` = one DNS label). |
166
- | `createProxyContext()` | `() => ProxyContext` | Creates a new `Map<string, unknown>` context instance. |
167
- | `isNextResult(value)` | `(value: unknown) => boolean` | Type guard for `next()` continuation tokens. |
168
- | `RuleTimeoutError` | `Error` | Thrown internally when `ruleTimeoutMs` is exceeded (catchable in `onError`). |
169
-
170
- ### Configuration Options (`ProxyChainOptions`)
171
-
172
- | Option | Type | Default | Description |
173
- | :--- | :--- | :--- | :--- |
174
- | `createContext` | `(req, event) => TContext` | `() => new Map()` | Factory for custom per-request context. Required for a non-`Map` `TContext`. |
175
- | `headerMergeStrategy` | `"last-write-wins" \| "first-write-wins" \| Function` | `"last-write-wins"` | Conflict strategy for **response** headers only. |
176
- | `cookieMergeStrategy` | `"last-write-wins" \| "first-write-wins" \| Function` | `"last-write-wins"` | Conflict strategy for `Set-Cookie` (same name+domain+path). |
177
- | `ruleTimeoutMs` | `number` | `0` | Wall-clock timeout per rule in ms (`0` disables). Does not abort the rule function; leftover rejections are swallowed. |
178
- | `onError` | `(err, index, req, ctx) => Response \| NextResult \| void` | `undefined` | Recovery hook. See **Errors** below. |
179
- | `requestHeaderPolicy` | `{ blocked?: string[], allowed?: string[] }` | `{}` | Blocklist/allowlist for **request** header mutations. |
180
- | `debug` | `boolean` | `false` | Structured one-line logs per rule. |
181
- | `logger` | `ChainLogger` | `console` | Custom logger (`debug`, `info`, `warn`, `error`). |
182
- | `strictOverrideCheck` | `boolean` | `false` | Throw at init if `NextResponse.next()` request overrides look unsupported. |
183
- | `hostFolderHeader` | `string` | unset | Opt-in: request header name that prefixes rewrites with a physical folder (e.g. `"x-internal-host-folder"`). Off by default. |
184
-
185
- ### Errors (`onError`)
186
-
187
- | `onError` returns | Behavior |
188
- | :--- | :--- |
189
- | `Response` | Stop and return that response (headers/cookies still merged). |
190
- | `next()` | Continue to the next rule (rule-level errors only). |
191
- | `undefined` / `void` / `null` | **Fail closed** — `500 Internal Server Error`. |
192
- | throws | `500 Internal Server Error`. |
193
- | omitted | Rule throw → `500`. |
194
-
195
- `ruleIndex` is `0`-based. `-1` means an engine-level error after context creation; only a `Response` is honored (the pipeline cannot continue).
196
-
197
- A logging-only `onError: (err) => { console.error(err) }` does **not** skip the failure.
198
-
199
- ### Return Value Protocol
200
-
201
- A rule (`ProxyFn`) can return:
202
-
203
- | Return Value | Behavior |
204
- | :--- | :--- |
205
- | `next({ request?, headers? })` | Continues. Queues request overrides, response headers, and `Set-Cookie`. |
206
- | `undefined` / `void` | Continues without mutations. |
207
- | `NextResponse.next()` | Continues; extracts Next.js request override headers and cookies. |
208
- | `NextResponse.rewrite(url)` | **Continues**. Stages a rewrite for later rules; the incoming `NextRequest` is not mutated. The rewrite is applied when the chain finishes unless a later rule returns a terminal response. |
209
- | `NextResponse.redirect(url)` | Stops immediately with the redirect. |
210
- | `Response` / `NextResponse.json()` | Stops immediately with that response. |
211
-
212
- ---
76
+ - Next.js: peer `>=15.0.0`. The test suite runs against Next.js 16.3.2. Next.js 15 `middleware.ts` is covered by integration tests that model its behavior, not by a Next.js 15 application.
77
+ - Node.js `>=20`, Bun `>=1`.
78
+ - Next.js 16 runs `proxy.ts` on the Node.js runtime by default. The package uses only Web platform APIs (`Headers`, `Request`, `Response`, `URL`), so it should also work on the Edge runtime, but that is not tested here.
213
79
 
214
80
  ## Links
215
81
 
216
- - [GitHub](https://github.com/klnap/next-proxy-chain)
217
-
218
- ---
82
+ - [Changelog](https://github.com/klnap/next-proxy-chain/blob/main/CHANGELOG.md)
83
+ - [Issues](https://github.com/klnap/next-proxy-chain/issues)
219
84
 
220
85
  ## License
221
86
 
222
- [MIT](./LICENSE)
223
-
87
+ [MIT](https://github.com/klnap/next-proxy-chain/blob/main/LICENSE)
package/dist/index.cjs CHANGED
@@ -216,16 +216,20 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
216
216
  function physicalFolderPrefix(raw) {
217
217
  return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
218
218
  }
219
+ function isInsideFolder(pathname, folder) {
220
+ if (folder === "/") return true;
221
+ return pathname === folder || pathname.startsWith(`${folder}/`);
222
+ }
219
223
  function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
220
224
  try {
221
225
  const parsed = new URL(rewriteUrl, baseUrl);
222
- if (!parsed.pathname.startsWith(folder)) {
226
+ if (!isInsideFolder(parsed.pathname, folder)) {
223
227
  parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
224
228
  return parsed.toString();
225
229
  }
226
230
  return rewriteUrl;
227
231
  } catch {
228
- if (!rewriteUrl.startsWith(folder)) {
232
+ if (!isInsideFolder(rewriteUrl, folder)) {
229
233
  return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
230
234
  }
231
235
  return rewriteUrl;
@@ -303,7 +307,12 @@ function isScopeObject(value) {
303
307
  return "host" in value || "path" in value;
304
308
  }
305
309
  function segmentToRegex(segment) {
306
- if (segment === "**") return "(?:.*)";
310
+ if (segment.includes("*") && segment !== "*" && segment !== "**") {
311
+ throw new Error(
312
+ `[proxy-chain] path segment "${segment}" mixes a wildcard with other characters. Use a whole-segment * or **.`
313
+ );
314
+ }
315
+ if (segment === "**") return "(?:[\\s\\S]*)";
307
316
  if (segment === "*") return "[^/]+";
308
317
  if (segment.startsWith(":")) return "[^/]+";
309
318
  return escapeRegex(segment);
@@ -323,7 +332,7 @@ function compileRegexPath(pattern) {
323
332
  const wrapFull = !hasStart && !hasEnd;
324
333
  const start = hasStart || wrapFull ? "^" : "";
325
334
  const end = hasEnd || wrapFull ? "$" : "";
326
- return toStatelessRegExp(new RegExp(`${start}${source}${end}`, pattern.flags));
335
+ return toStatelessRegExp(new RegExp(`${start}(?:${source})${end}`, pattern.flags));
327
336
  }
328
337
  function compileStringPath(pattern) {
329
338
  const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
@@ -339,7 +348,7 @@ function compileStringPath(pattern) {
339
348
  pathPattern = prefix ? `/${prefix}/[^/]+` : `/[^/]+`;
340
349
  } else if (trailingGlobstar) {
341
350
  const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
342
- pathPattern = prefix ? `/${prefix}(?:/.*)?` : `/(?:.*)?`;
351
+ pathPattern = prefix ? `/${prefix}(?:/[\\s\\S]*)?` : `/(?:[\\s\\S]*)?`;
343
352
  } else {
344
353
  pathPattern = `/${segments.map(segmentToRegex).join("/")}`;
345
354
  }
@@ -396,10 +405,17 @@ function toRule(entry) {
396
405
  const rule = entry;
397
406
  const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
398
407
  const name = extractMeaningfulName(rule.name) ?? runName;
399
- const harden = (scopes) => scopes?.map((s) => ({
400
- host: s.host ? toStatelessRegExp(s.host) : void 0,
401
- path: s.path ? toStatelessRegExp(s.path) : void 0
402
- }));
408
+ const harden = (scopes) => scopes?.map((s) => {
409
+ if (!s.host && !s.path) {
410
+ throw new Error(
411
+ "[proxy-chain] include/exclude scope needs `host` or `path`. Build scopes with path() or host()."
412
+ );
413
+ }
414
+ return {
415
+ host: s.host ? toStatelessRegExp(s.host) : void 0,
416
+ path: s.path ? toStatelessRegExp(s.path) : void 0
417
+ };
418
+ });
403
419
  return {
404
420
  ...rule,
405
421
  name: name ?? void 0,
@@ -434,9 +450,18 @@ function normalizeHost(raw) {
434
450
  const end = first.indexOf("]");
435
451
  return end === -1 ? first : first.slice(1, end);
436
452
  }
437
- const withoutPort = first.replace(/:\d+$/, "");
453
+ const withoutPort = first.replace(/:\d+$/, "").replace(/\.$/, "");
438
454
  return withoutPort || null;
439
455
  }
456
+ function canonicalPathname(pathname) {
457
+ let decoded;
458
+ try {
459
+ decoded = decodeURIComponent(pathname);
460
+ } catch {
461
+ return null;
462
+ }
463
+ return decoded.length > 1 ? decoded.replace(/\/+$/, "") || "/" : decoded;
464
+ }
440
465
  function scopeKey(scope) {
441
466
  return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
442
467
  }
@@ -469,7 +494,8 @@ function runOverrideProbe() {
469
494
  const testRes = import_server.NextResponse.next({
470
495
  request: { headers: new Headers({ "x-proxy-chain-probe": "1" }) }
471
496
  });
472
- return testRes.headers.get("x-middleware-next") === "1";
497
+ const overridden = (testRes.headers.get("x-middleware-override-headers") ?? "").split(",").map((name) => name.trim());
498
+ return testRes.headers.get("x-middleware-next") === "1" && overridden.includes("x-proxy-chain-probe") && testRes.headers.get("x-middleware-request-x-proxy-chain-probe") === "1";
473
499
  }
474
500
  function throwForCachedProbe(probe) {
475
501
  if (probe.kind === "unsupported") throw new Error(UNSUPPORTED_OVERRIDE_MSG);
@@ -503,6 +529,11 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
503
529
  if (res == null) {
504
530
  return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
505
531
  }
532
+ if (!isNextResult(res) && !(res instanceof Response)) {
533
+ throw new TypeError(
534
+ `[proxy-chain] rule must return next(), a Response, or undefined. Got ${typeof res}.`
535
+ );
536
+ }
506
537
  if (isNextResult(res)) {
507
538
  let request;
508
539
  if (res.request) {
@@ -525,7 +556,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
525
556
  cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
526
557
  };
527
558
  }
528
- if (res.headers.get("x-middleware-next") === "1") {
559
+ if (res instanceof import_server.NextResponse && res.headers.get("x-middleware-next") === "1") {
529
560
  let request;
530
561
  const decoded = decodeOverriddenRequestHeaders(res.headers);
531
562
  if ([...decoded.keys()].length > 0) {
@@ -540,7 +571,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
540
571
  cookies: cookieItemsFromHeaders(res.headers)
541
572
  };
542
573
  }
543
- const rewriteHeader = res.headers.get("x-middleware-rewrite");
574
+ const rewriteHeader = res instanceof import_server.NextResponse ? res.headers.get("x-middleware-rewrite") : null;
544
575
  if (rewriteHeader && (res.status === 200 || !res.status)) {
545
576
  let request;
546
577
  const decoded = decodeOverriddenRequestHeaders(res.headers);
@@ -574,8 +605,19 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
574
605
  for (const key of seenHeaders) {
575
606
  if (!headers.has(key)) dropHeaders.push(key);
576
607
  }
577
- applyMergedToResponse(res, headers, cookies, dropHeaders);
578
- return res;
608
+ try {
609
+ applyMergedToResponse(res, headers, cookies, dropHeaders);
610
+ return res;
611
+ } catch (err) {
612
+ if (!(err instanceof TypeError)) throw err;
613
+ const copy = new Response(res.body, {
614
+ status: res.status,
615
+ statusText: res.statusText,
616
+ headers: new Headers(res.headers)
617
+ });
618
+ applyMergedToResponse(copy, headers, cookies, dropHeaders);
619
+ return copy;
620
+ }
579
621
  }
580
622
 
581
623
  // src/core/timeout.ts
@@ -590,9 +632,9 @@ var RuleTimeoutError = class extends Error {
590
632
  }
591
633
  };
592
634
  function assertFiniteRuleTimeoutMs(ruleTimeoutMs) {
593
- if (ruleTimeoutMs != null && !Number.isFinite(ruleTimeoutMs)) {
635
+ if (ruleTimeoutMs != null && (!Number.isFinite(ruleTimeoutMs) || ruleTimeoutMs < 0)) {
594
636
  throw new RangeError(
595
- `[proxy-chain] ruleTimeoutMs must be a finite positive number, got ${ruleTimeoutMs}`
637
+ `[proxy-chain] ruleTimeoutMs must be a finite number >= 0 (0 disables), got ${ruleTimeoutMs}`
596
638
  );
597
639
  }
598
640
  }
@@ -613,6 +655,18 @@ async function withRuleTimeout(promise, timeoutMs, ruleName) {
613
655
  }
614
656
 
615
657
  // src/core/engine.ts
658
+ function isNextResponse(value) {
659
+ return value instanceof import_server2.NextResponse && value.headers.get("x-middleware-next") === "1";
660
+ }
661
+ function stripRoutingOverrides(res) {
662
+ const plain = !(res instanceof import_server2.NextResponse);
663
+ for (const key of [...res.headers.keys()]) {
664
+ const lower = key.toLowerCase();
665
+ if (lower === "x-middleware-override-headers" || lower.startsWith("x-middleware-request-") || plain && (lower === "x-middleware-next" || lower === "x-middleware-rewrite")) {
666
+ res.headers.delete(key);
667
+ }
668
+ }
669
+ }
616
670
  function isPathFilter(value) {
617
671
  if (value === null || typeof value !== "object") return false;
618
672
  if ("nextUrl" in value) return false;
@@ -690,6 +744,15 @@ function proxyChain(optionsOrEntries, maybeEntries) {
690
744
  let pendingRewriteUrl = null;
691
745
  const headerWrites = [];
692
746
  const cookieWrites = [];
747
+ const failClosed = () => finalizeResponse(
748
+ safeInternalError(),
749
+ headerWrites,
750
+ cookieWrites,
751
+ headerMergeStrategy,
752
+ cookieMergeStrategy,
753
+ logger,
754
+ debug
755
+ );
693
756
  const materializeRequest = () => {
694
757
  if (!pendingRequestOverrides) return currentReq;
695
758
  if (!headersDiffer(currentReq.headers, pendingRequestOverrides)) {
@@ -713,6 +776,58 @@ function proxyChain(optionsOrEntries, maybeEntries) {
713
776
  appliedRequestOverrides.set(k, v);
714
777
  });
715
778
  };
779
+ const recoverRuleError = async (err, i, label, req2, startedAt) => {
780
+ if (!config.onError) {
781
+ logger.error({ rule: label, err }, "rule threw");
782
+ return { response: failClosed() };
783
+ }
784
+ try {
785
+ const recovered = await config.onError(err, i, req2, ctx);
786
+ if (recovered == null) return { response: failClosed() };
787
+ if (isNextResult(recovered) || isNextResponse(recovered)) return { raw: recovered };
788
+ if (!(recovered instanceof Response)) return { response: failClosed() };
789
+ stripRoutingOverrides(recovered);
790
+ headerWrites.push({
791
+ ruleIndex: i,
792
+ ruleName: label,
793
+ items: responseHeaderItems(recovered.headers)
794
+ });
795
+ cookieWrites.push({
796
+ ruleIndex: i,
797
+ ruleName: label,
798
+ items: cookieItemsFromHeaders(recovered.headers)
799
+ });
800
+ if (debug) {
801
+ logger.debug(
802
+ formatPipelineLine({
803
+ method,
804
+ path: pathname,
805
+ name: label,
806
+ traceId,
807
+ outcome: {
808
+ kind: "stop",
809
+ duration: performance.now() - startedAt,
810
+ status: recovered.status
811
+ }
812
+ })
813
+ );
814
+ }
815
+ return {
816
+ response: finalizeResponse(
817
+ recovered,
818
+ headerWrites,
819
+ cookieWrites,
820
+ headerMergeStrategy,
821
+ cookieMergeStrategy,
822
+ logger,
823
+ debug
824
+ )
825
+ };
826
+ } catch (onErrorErr) {
827
+ logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
828
+ return { response: failClosed() };
829
+ }
830
+ };
716
831
  try {
717
832
  for (let i = 0; i < rules.length; i++) {
718
833
  const rule = rules[i];
@@ -721,7 +836,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
721
836
  const reqHost = normalizeHost(
722
837
  activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
723
838
  );
724
- if (!ruleMatches(activeReq.nextUrl.pathname, reqHost, rule)) continue;
839
+ const matchPath = canonicalPathname(activeReq.nextUrl.pathname);
840
+ if (matchPath === null) {
841
+ return new import_server2.NextResponse("Bad Request", {
842
+ status: 400,
843
+ headers: { "content-type": "text/plain; charset=utf-8" }
844
+ });
845
+ }
846
+ if (!ruleMatches(matchPath, reqHost, rule)) continue;
725
847
  const startedAt = debug ? performance.now() : 0;
726
848
  let raw;
727
849
  try {
@@ -731,60 +853,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
731
853
  label
732
854
  );
733
855
  } catch (err) {
734
- if (config.onError) {
735
- try {
736
- const recovered = await config.onError(err, i, activeReq, ctx);
737
- if (recovered == null) return safeInternalError();
738
- if (isNextResult(recovered)) {
739
- raw = recovered;
740
- } else if (recovered instanceof Response) {
741
- headerWrites.push({
742
- ruleIndex: i,
743
- ruleName: label,
744
- items: responseHeaderItems(recovered.headers)
745
- });
746
- cookieWrites.push({
747
- ruleIndex: i,
748
- ruleName: label,
749
- items: cookieItemsFromHeaders(recovered.headers)
750
- });
751
- if (debug) {
752
- logger.debug(
753
- formatPipelineLine({
754
- method,
755
- path: pathname,
756
- name: label,
757
- traceId,
758
- outcome: {
759
- kind: "stop",
760
- duration: performance.now() - startedAt,
761
- status: recovered.status
762
- }
763
- })
764
- );
765
- }
766
- return finalizeResponse(
767
- recovered,
768
- headerWrites,
769
- cookieWrites,
770
- headerMergeStrategy,
771
- cookieMergeStrategy,
772
- logger,
773
- debug
774
- );
775
- } else {
776
- return safeInternalError();
777
- }
778
- } catch (onErrorErr) {
779
- logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
780
- return safeInternalError();
781
- }
782
- } else {
783
- logger.error({ rule: label, err }, "rule threw");
784
- return safeInternalError();
785
- }
856
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
857
+ if ("response" in recovered) return recovered.response;
858
+ raw = recovered.raw;
859
+ }
860
+ let outcome;
861
+ try {
862
+ outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
863
+ } catch (err) {
864
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
865
+ if ("response" in recovered) return recovered.response;
866
+ outcome = resolveRuleResult(recovered.raw, requestHeaderPolicy, logger, debug);
786
867
  }
787
- const outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
788
868
  const duration = debug ? performance.now() - startedAt : 0;
789
869
  if (outcome.kind === "continue") {
790
870
  if (outcome.rewriteUrl) {
@@ -819,6 +899,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
819
899
  }
820
900
  continue;
821
901
  }
902
+ stripRoutingOverrides(outcome.response);
822
903
  headerWrites.push({
823
904
  ruleIndex: i,
824
905
  ruleName: label,
@@ -872,19 +953,20 @@ function proxyChain(optionsOrEntries, maybeEntries) {
872
953
  finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
873
954
  } else {
874
955
  const currentPath = finalReq.nextUrl.pathname;
875
- if (!currentPath.startsWith(cleanFolder)) {
956
+ if (!isInsideFolder(currentPath, cleanFolder)) {
876
957
  const targetUrl = finalReq.nextUrl.clone();
877
958
  targetUrl.pathname = cleanFolder + (currentPath === "/" ? "" : currentPath);
878
959
  finalRewriteUrl = targetUrl.toString();
879
960
  }
880
961
  }
881
962
  }
963
+ const requestInit = finalReq !== req ? { request: { headers: finalReq.headers } } : void 0;
882
964
  let final;
883
965
  if (finalRewriteUrl) {
884
966
  const rewriteTarget = new URL(finalRewriteUrl, finalReq.url);
885
- final = import_server2.NextResponse.rewrite(rewriteTarget, { request: { headers: finalReq.headers } });
967
+ final = import_server2.NextResponse.rewrite(rewriteTarget, requestInit);
886
968
  } else {
887
- final = import_server2.NextResponse.next({ request: { headers: finalReq.headers } });
969
+ final = import_server2.NextResponse.next(requestInit);
888
970
  }
889
971
  return finalizeResponse(
890
972
  final,
@@ -900,11 +982,22 @@ function proxyChain(optionsOrEntries, maybeEntries) {
900
982
  if (config.onError) {
901
983
  try {
902
984
  const recovered = await config.onError(err, -1, materializeRequest(), ctx);
903
- if (recovered instanceof Response) return recovered;
985
+ if (recovered instanceof Response && !isNextResponse(recovered)) {
986
+ stripRoutingOverrides(recovered);
987
+ return finalizeResponse(
988
+ recovered,
989
+ headerWrites,
990
+ cookieWrites,
991
+ headerMergeStrategy,
992
+ cookieMergeStrategy,
993
+ logger,
994
+ debug
995
+ );
996
+ }
904
997
  } catch {
905
998
  }
906
999
  }
907
- return safeInternalError();
1000
+ return failClosed();
908
1001
  }
909
1002
  };
910
1003
  }
package/dist/index.js CHANGED
@@ -183,16 +183,20 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
183
183
  function physicalFolderPrefix(raw) {
184
184
  return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
185
185
  }
186
+ function isInsideFolder(pathname, folder) {
187
+ if (folder === "/") return true;
188
+ return pathname === folder || pathname.startsWith(`${folder}/`);
189
+ }
186
190
  function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
187
191
  try {
188
192
  const parsed = new URL(rewriteUrl, baseUrl);
189
- if (!parsed.pathname.startsWith(folder)) {
193
+ if (!isInsideFolder(parsed.pathname, folder)) {
190
194
  parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
191
195
  return parsed.toString();
192
196
  }
193
197
  return rewriteUrl;
194
198
  } catch {
195
- if (!rewriteUrl.startsWith(folder)) {
199
+ if (!isInsideFolder(rewriteUrl, folder)) {
196
200
  return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
197
201
  }
198
202
  return rewriteUrl;
@@ -270,7 +274,12 @@ function isScopeObject(value) {
270
274
  return "host" in value || "path" in value;
271
275
  }
272
276
  function segmentToRegex(segment) {
273
- if (segment === "**") return "(?:.*)";
277
+ if (segment.includes("*") && segment !== "*" && segment !== "**") {
278
+ throw new Error(
279
+ `[proxy-chain] path segment "${segment}" mixes a wildcard with other characters. Use a whole-segment * or **.`
280
+ );
281
+ }
282
+ if (segment === "**") return "(?:[\\s\\S]*)";
274
283
  if (segment === "*") return "[^/]+";
275
284
  if (segment.startsWith(":")) return "[^/]+";
276
285
  return escapeRegex(segment);
@@ -290,7 +299,7 @@ function compileRegexPath(pattern) {
290
299
  const wrapFull = !hasStart && !hasEnd;
291
300
  const start = hasStart || wrapFull ? "^" : "";
292
301
  const end = hasEnd || wrapFull ? "$" : "";
293
- return toStatelessRegExp(new RegExp(`${start}${source}${end}`, pattern.flags));
302
+ return toStatelessRegExp(new RegExp(`${start}(?:${source})${end}`, pattern.flags));
294
303
  }
295
304
  function compileStringPath(pattern) {
296
305
  const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
@@ -306,7 +315,7 @@ function compileStringPath(pattern) {
306
315
  pathPattern = prefix ? `/${prefix}/[^/]+` : `/[^/]+`;
307
316
  } else if (trailingGlobstar) {
308
317
  const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
309
- pathPattern = prefix ? `/${prefix}(?:/.*)?` : `/(?:.*)?`;
318
+ pathPattern = prefix ? `/${prefix}(?:/[\\s\\S]*)?` : `/(?:[\\s\\S]*)?`;
310
319
  } else {
311
320
  pathPattern = `/${segments.map(segmentToRegex).join("/")}`;
312
321
  }
@@ -363,10 +372,17 @@ function toRule(entry) {
363
372
  const rule = entry;
364
373
  const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
365
374
  const name = extractMeaningfulName(rule.name) ?? runName;
366
- const harden = (scopes) => scopes?.map((s) => ({
367
- host: s.host ? toStatelessRegExp(s.host) : void 0,
368
- path: s.path ? toStatelessRegExp(s.path) : void 0
369
- }));
375
+ const harden = (scopes) => scopes?.map((s) => {
376
+ if (!s.host && !s.path) {
377
+ throw new Error(
378
+ "[proxy-chain] include/exclude scope needs `host` or `path`. Build scopes with path() or host()."
379
+ );
380
+ }
381
+ return {
382
+ host: s.host ? toStatelessRegExp(s.host) : void 0,
383
+ path: s.path ? toStatelessRegExp(s.path) : void 0
384
+ };
385
+ });
370
386
  return {
371
387
  ...rule,
372
388
  name: name ?? void 0,
@@ -401,9 +417,18 @@ function normalizeHost(raw) {
401
417
  const end = first.indexOf("]");
402
418
  return end === -1 ? first : first.slice(1, end);
403
419
  }
404
- const withoutPort = first.replace(/:\d+$/, "");
420
+ const withoutPort = first.replace(/:\d+$/, "").replace(/\.$/, "");
405
421
  return withoutPort || null;
406
422
  }
423
+ function canonicalPathname(pathname) {
424
+ let decoded;
425
+ try {
426
+ decoded = decodeURIComponent(pathname);
427
+ } catch {
428
+ return null;
429
+ }
430
+ return decoded.length > 1 ? decoded.replace(/\/+$/, "") || "/" : decoded;
431
+ }
407
432
  function scopeKey(scope) {
408
433
  return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
409
434
  }
@@ -436,7 +461,8 @@ function runOverrideProbe() {
436
461
  const testRes = NextResponse.next({
437
462
  request: { headers: new Headers({ "x-proxy-chain-probe": "1" }) }
438
463
  });
439
- return testRes.headers.get("x-middleware-next") === "1";
464
+ const overridden = (testRes.headers.get("x-middleware-override-headers") ?? "").split(",").map((name) => name.trim());
465
+ return testRes.headers.get("x-middleware-next") === "1" && overridden.includes("x-proxy-chain-probe") && testRes.headers.get("x-middleware-request-x-proxy-chain-probe") === "1";
440
466
  }
441
467
  function throwForCachedProbe(probe) {
442
468
  if (probe.kind === "unsupported") throw new Error(UNSUPPORTED_OVERRIDE_MSG);
@@ -470,6 +496,11 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
470
496
  if (res == null) {
471
497
  return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
472
498
  }
499
+ if (!isNextResult(res) && !(res instanceof Response)) {
500
+ throw new TypeError(
501
+ `[proxy-chain] rule must return next(), a Response, or undefined. Got ${typeof res}.`
502
+ );
503
+ }
473
504
  if (isNextResult(res)) {
474
505
  let request;
475
506
  if (res.request) {
@@ -492,7 +523,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
492
523
  cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
493
524
  };
494
525
  }
495
- if (res.headers.get("x-middleware-next") === "1") {
526
+ if (res instanceof NextResponse && res.headers.get("x-middleware-next") === "1") {
496
527
  let request;
497
528
  const decoded = decodeOverriddenRequestHeaders(res.headers);
498
529
  if ([...decoded.keys()].length > 0) {
@@ -507,7 +538,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
507
538
  cookies: cookieItemsFromHeaders(res.headers)
508
539
  };
509
540
  }
510
- const rewriteHeader = res.headers.get("x-middleware-rewrite");
541
+ const rewriteHeader = res instanceof NextResponse ? res.headers.get("x-middleware-rewrite") : null;
511
542
  if (rewriteHeader && (res.status === 200 || !res.status)) {
512
543
  let request;
513
544
  const decoded = decodeOverriddenRequestHeaders(res.headers);
@@ -541,8 +572,19 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
541
572
  for (const key of seenHeaders) {
542
573
  if (!headers.has(key)) dropHeaders.push(key);
543
574
  }
544
- applyMergedToResponse(res, headers, cookies, dropHeaders);
545
- return res;
575
+ try {
576
+ applyMergedToResponse(res, headers, cookies, dropHeaders);
577
+ return res;
578
+ } catch (err) {
579
+ if (!(err instanceof TypeError)) throw err;
580
+ const copy = new Response(res.body, {
581
+ status: res.status,
582
+ statusText: res.statusText,
583
+ headers: new Headers(res.headers)
584
+ });
585
+ applyMergedToResponse(copy, headers, cookies, dropHeaders);
586
+ return copy;
587
+ }
546
588
  }
547
589
 
548
590
  // src/core/timeout.ts
@@ -557,9 +599,9 @@ var RuleTimeoutError = class extends Error {
557
599
  }
558
600
  };
559
601
  function assertFiniteRuleTimeoutMs(ruleTimeoutMs) {
560
- if (ruleTimeoutMs != null && !Number.isFinite(ruleTimeoutMs)) {
602
+ if (ruleTimeoutMs != null && (!Number.isFinite(ruleTimeoutMs) || ruleTimeoutMs < 0)) {
561
603
  throw new RangeError(
562
- `[proxy-chain] ruleTimeoutMs must be a finite positive number, got ${ruleTimeoutMs}`
604
+ `[proxy-chain] ruleTimeoutMs must be a finite number >= 0 (0 disables), got ${ruleTimeoutMs}`
563
605
  );
564
606
  }
565
607
  }
@@ -580,6 +622,18 @@ async function withRuleTimeout(promise, timeoutMs, ruleName) {
580
622
  }
581
623
 
582
624
  // src/core/engine.ts
625
+ function isNextResponse(value) {
626
+ return value instanceof NextResponse2 && value.headers.get("x-middleware-next") === "1";
627
+ }
628
+ function stripRoutingOverrides(res) {
629
+ const plain = !(res instanceof NextResponse2);
630
+ for (const key of [...res.headers.keys()]) {
631
+ const lower = key.toLowerCase();
632
+ if (lower === "x-middleware-override-headers" || lower.startsWith("x-middleware-request-") || plain && (lower === "x-middleware-next" || lower === "x-middleware-rewrite")) {
633
+ res.headers.delete(key);
634
+ }
635
+ }
636
+ }
583
637
  function isPathFilter(value) {
584
638
  if (value === null || typeof value !== "object") return false;
585
639
  if ("nextUrl" in value) return false;
@@ -657,6 +711,15 @@ function proxyChain(optionsOrEntries, maybeEntries) {
657
711
  let pendingRewriteUrl = null;
658
712
  const headerWrites = [];
659
713
  const cookieWrites = [];
714
+ const failClosed = () => finalizeResponse(
715
+ safeInternalError(),
716
+ headerWrites,
717
+ cookieWrites,
718
+ headerMergeStrategy,
719
+ cookieMergeStrategy,
720
+ logger,
721
+ debug
722
+ );
660
723
  const materializeRequest = () => {
661
724
  if (!pendingRequestOverrides) return currentReq;
662
725
  if (!headersDiffer(currentReq.headers, pendingRequestOverrides)) {
@@ -680,6 +743,58 @@ function proxyChain(optionsOrEntries, maybeEntries) {
680
743
  appliedRequestOverrides.set(k, v);
681
744
  });
682
745
  };
746
+ const recoverRuleError = async (err, i, label, req2, startedAt) => {
747
+ if (!config.onError) {
748
+ logger.error({ rule: label, err }, "rule threw");
749
+ return { response: failClosed() };
750
+ }
751
+ try {
752
+ const recovered = await config.onError(err, i, req2, ctx);
753
+ if (recovered == null) return { response: failClosed() };
754
+ if (isNextResult(recovered) || isNextResponse(recovered)) return { raw: recovered };
755
+ if (!(recovered instanceof Response)) return { response: failClosed() };
756
+ stripRoutingOverrides(recovered);
757
+ headerWrites.push({
758
+ ruleIndex: i,
759
+ ruleName: label,
760
+ items: responseHeaderItems(recovered.headers)
761
+ });
762
+ cookieWrites.push({
763
+ ruleIndex: i,
764
+ ruleName: label,
765
+ items: cookieItemsFromHeaders(recovered.headers)
766
+ });
767
+ if (debug) {
768
+ logger.debug(
769
+ formatPipelineLine({
770
+ method,
771
+ path: pathname,
772
+ name: label,
773
+ traceId,
774
+ outcome: {
775
+ kind: "stop",
776
+ duration: performance.now() - startedAt,
777
+ status: recovered.status
778
+ }
779
+ })
780
+ );
781
+ }
782
+ return {
783
+ response: finalizeResponse(
784
+ recovered,
785
+ headerWrites,
786
+ cookieWrites,
787
+ headerMergeStrategy,
788
+ cookieMergeStrategy,
789
+ logger,
790
+ debug
791
+ )
792
+ };
793
+ } catch (onErrorErr) {
794
+ logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
795
+ return { response: failClosed() };
796
+ }
797
+ };
683
798
  try {
684
799
  for (let i = 0; i < rules.length; i++) {
685
800
  const rule = rules[i];
@@ -688,7 +803,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
688
803
  const reqHost = normalizeHost(
689
804
  activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
690
805
  );
691
- if (!ruleMatches(activeReq.nextUrl.pathname, reqHost, rule)) continue;
806
+ const matchPath = canonicalPathname(activeReq.nextUrl.pathname);
807
+ if (matchPath === null) {
808
+ return new NextResponse2("Bad Request", {
809
+ status: 400,
810
+ headers: { "content-type": "text/plain; charset=utf-8" }
811
+ });
812
+ }
813
+ if (!ruleMatches(matchPath, reqHost, rule)) continue;
692
814
  const startedAt = debug ? performance.now() : 0;
693
815
  let raw;
694
816
  try {
@@ -698,60 +820,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
698
820
  label
699
821
  );
700
822
  } catch (err) {
701
- if (config.onError) {
702
- try {
703
- const recovered = await config.onError(err, i, activeReq, ctx);
704
- if (recovered == null) return safeInternalError();
705
- if (isNextResult(recovered)) {
706
- raw = recovered;
707
- } else if (recovered instanceof Response) {
708
- headerWrites.push({
709
- ruleIndex: i,
710
- ruleName: label,
711
- items: responseHeaderItems(recovered.headers)
712
- });
713
- cookieWrites.push({
714
- ruleIndex: i,
715
- ruleName: label,
716
- items: cookieItemsFromHeaders(recovered.headers)
717
- });
718
- if (debug) {
719
- logger.debug(
720
- formatPipelineLine({
721
- method,
722
- path: pathname,
723
- name: label,
724
- traceId,
725
- outcome: {
726
- kind: "stop",
727
- duration: performance.now() - startedAt,
728
- status: recovered.status
729
- }
730
- })
731
- );
732
- }
733
- return finalizeResponse(
734
- recovered,
735
- headerWrites,
736
- cookieWrites,
737
- headerMergeStrategy,
738
- cookieMergeStrategy,
739
- logger,
740
- debug
741
- );
742
- } else {
743
- return safeInternalError();
744
- }
745
- } catch (onErrorErr) {
746
- logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
747
- return safeInternalError();
748
- }
749
- } else {
750
- logger.error({ rule: label, err }, "rule threw");
751
- return safeInternalError();
752
- }
823
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
824
+ if ("response" in recovered) return recovered.response;
825
+ raw = recovered.raw;
826
+ }
827
+ let outcome;
828
+ try {
829
+ outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
830
+ } catch (err) {
831
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
832
+ if ("response" in recovered) return recovered.response;
833
+ outcome = resolveRuleResult(recovered.raw, requestHeaderPolicy, logger, debug);
753
834
  }
754
- const outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
755
835
  const duration = debug ? performance.now() - startedAt : 0;
756
836
  if (outcome.kind === "continue") {
757
837
  if (outcome.rewriteUrl) {
@@ -786,6 +866,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
786
866
  }
787
867
  continue;
788
868
  }
869
+ stripRoutingOverrides(outcome.response);
789
870
  headerWrites.push({
790
871
  ruleIndex: i,
791
872
  ruleName: label,
@@ -839,19 +920,20 @@ function proxyChain(optionsOrEntries, maybeEntries) {
839
920
  finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
840
921
  } else {
841
922
  const currentPath = finalReq.nextUrl.pathname;
842
- if (!currentPath.startsWith(cleanFolder)) {
923
+ if (!isInsideFolder(currentPath, cleanFolder)) {
843
924
  const targetUrl = finalReq.nextUrl.clone();
844
925
  targetUrl.pathname = cleanFolder + (currentPath === "/" ? "" : currentPath);
845
926
  finalRewriteUrl = targetUrl.toString();
846
927
  }
847
928
  }
848
929
  }
930
+ const requestInit = finalReq !== req ? { request: { headers: finalReq.headers } } : void 0;
849
931
  let final;
850
932
  if (finalRewriteUrl) {
851
933
  const rewriteTarget = new URL(finalRewriteUrl, finalReq.url);
852
- final = NextResponse2.rewrite(rewriteTarget, { request: { headers: finalReq.headers } });
934
+ final = NextResponse2.rewrite(rewriteTarget, requestInit);
853
935
  } else {
854
- final = NextResponse2.next({ request: { headers: finalReq.headers } });
936
+ final = NextResponse2.next(requestInit);
855
937
  }
856
938
  return finalizeResponse(
857
939
  final,
@@ -867,11 +949,22 @@ function proxyChain(optionsOrEntries, maybeEntries) {
867
949
  if (config.onError) {
868
950
  try {
869
951
  const recovered = await config.onError(err, -1, materializeRequest(), ctx);
870
- if (recovered instanceof Response) return recovered;
952
+ if (recovered instanceof Response && !isNextResponse(recovered)) {
953
+ stripRoutingOverrides(recovered);
954
+ return finalizeResponse(
955
+ recovered,
956
+ headerWrites,
957
+ cookieWrites,
958
+ headerMergeStrategy,
959
+ cookieMergeStrategy,
960
+ logger,
961
+ debug
962
+ );
963
+ }
871
964
  } catch {
872
965
  }
873
966
  }
874
- return safeInternalError();
967
+ return failClosed();
875
968
  }
876
969
  };
877
970
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@klnap/next-proxy-chain",
3
- "version": "1.0.5",
4
- "description": "Composable request pipeline for Next.js middleware and proxy.",
3
+ "version": "1.0.7",
4
+ "description": "Compose independent request rules for Next.js proxy.ts and middleware.ts.",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/klnap/next-proxy-chain.git"