@klnap/next-proxy-chain 1.0.5 → 1.0.6

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,34 @@ 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.6] - 2026-11-22
8
+
9
+ ### Fixed
10
+
11
+ - `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`.
12
+ - Engine-level `onError` responses merge headers and cookies from earlier rules.
13
+ - Scope matching uses the percent-decoded, trailing-slash-free path. `include: path("/admin/**")` no longer misses `/%61dmin/…` or `/admin/`.
14
+ - `**` 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.
15
+ - Malformed percent-encoding returns `400` instead of skipping rules.
16
+ - Regex path patterns keep top-level alternation inside their anchors (`path(/\/public|\/static/)` no longer matches `/admin/static`).
17
+ - A trailing dot in the `Host` header is ignored when matching host scopes.
18
+ - A malformed rule return (for example a string) is reported to `onError` with that rule's index instead of `-1`.
19
+ - 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.
20
+
21
+ ### Security
22
+
23
+ - 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.
24
+ - Bare object scopes (`{ run, include }` with a RegExp instead of `path()`/`host()`) throw at startup. Before, they matched every request.
25
+ - 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.
26
+ - `ruleTimeoutMs` rejects negative values. Before, they silently disabled the timeout.
27
+ - CI workflow: read-only `GITHUB_TOKEN` permissions, no persisted checkout credentials, actions pinned to commit SHAs.
28
+
29
+ ### Documentation
30
+
31
+ - README rewritten around adoption: what the package does, when to use it, a quick start that puts the security header first.
32
+ - New `docs/` section: concepts (execution model), guides, API reference, security notes.
33
+ - `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.
34
+ - API notes: `headers` on proxy responses, one-sided RegExp anchors, `-1` error index, `*` and `**` as whole segments, Server Functions and matchers.
8
35
 
9
36
  ## [1.0.5] - 2026-10-29
10
37
 
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
@@ -303,7 +303,12 @@ function isScopeObject(value) {
303
303
  return "host" in value || "path" in value;
304
304
  }
305
305
  function segmentToRegex(segment) {
306
- if (segment === "**") return "(?:.*)";
306
+ if (segment.includes("*") && segment !== "*" && segment !== "**") {
307
+ throw new Error(
308
+ `[proxy-chain] path segment "${segment}" mixes a wildcard with other characters. Use a whole-segment * or **.`
309
+ );
310
+ }
311
+ if (segment === "**") return "(?:[\\s\\S]*)";
307
312
  if (segment === "*") return "[^/]+";
308
313
  if (segment.startsWith(":")) return "[^/]+";
309
314
  return escapeRegex(segment);
@@ -323,7 +328,7 @@ function compileRegexPath(pattern) {
323
328
  const wrapFull = !hasStart && !hasEnd;
324
329
  const start = hasStart || wrapFull ? "^" : "";
325
330
  const end = hasEnd || wrapFull ? "$" : "";
326
- return toStatelessRegExp(new RegExp(`${start}${source}${end}`, pattern.flags));
331
+ return toStatelessRegExp(new RegExp(`${start}(?:${source})${end}`, pattern.flags));
327
332
  }
328
333
  function compileStringPath(pattern) {
329
334
  const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
@@ -339,7 +344,7 @@ function compileStringPath(pattern) {
339
344
  pathPattern = prefix ? `/${prefix}/[^/]+` : `/[^/]+`;
340
345
  } else if (trailingGlobstar) {
341
346
  const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
342
- pathPattern = prefix ? `/${prefix}(?:/.*)?` : `/(?:.*)?`;
347
+ pathPattern = prefix ? `/${prefix}(?:/[\\s\\S]*)?` : `/(?:[\\s\\S]*)?`;
343
348
  } else {
344
349
  pathPattern = `/${segments.map(segmentToRegex).join("/")}`;
345
350
  }
@@ -396,10 +401,17 @@ function toRule(entry) {
396
401
  const rule = entry;
397
402
  const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
398
403
  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
- }));
404
+ const harden = (scopes) => scopes?.map((s) => {
405
+ if (!s.host && !s.path) {
406
+ throw new Error(
407
+ "[proxy-chain] include/exclude scope needs `host` or `path`. Build scopes with path() or host()."
408
+ );
409
+ }
410
+ return {
411
+ host: s.host ? toStatelessRegExp(s.host) : void 0,
412
+ path: s.path ? toStatelessRegExp(s.path) : void 0
413
+ };
414
+ });
403
415
  return {
404
416
  ...rule,
405
417
  name: name ?? void 0,
@@ -434,9 +446,18 @@ function normalizeHost(raw) {
434
446
  const end = first.indexOf("]");
435
447
  return end === -1 ? first : first.slice(1, end);
436
448
  }
437
- const withoutPort = first.replace(/:\d+$/, "");
449
+ const withoutPort = first.replace(/:\d+$/, "").replace(/\.$/, "");
438
450
  return withoutPort || null;
439
451
  }
452
+ function canonicalPathname(pathname) {
453
+ let decoded;
454
+ try {
455
+ decoded = decodeURIComponent(pathname);
456
+ } catch {
457
+ return null;
458
+ }
459
+ return decoded.length > 1 ? decoded.replace(/\/+$/, "") || "/" : decoded;
460
+ }
440
461
  function scopeKey(scope) {
441
462
  return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
442
463
  }
@@ -503,6 +524,11 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
503
524
  if (res == null) {
504
525
  return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
505
526
  }
527
+ if (!isNextResult(res) && !(res instanceof Response)) {
528
+ throw new TypeError(
529
+ `[proxy-chain] rule must return next(), a Response, or undefined. Got ${typeof res}.`
530
+ );
531
+ }
506
532
  if (isNextResult(res)) {
507
533
  let request;
508
534
  if (res.request) {
@@ -525,7 +551,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
525
551
  cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
526
552
  };
527
553
  }
528
- if (res.headers.get("x-middleware-next") === "1") {
554
+ if (res instanceof import_server.NextResponse && res.headers.get("x-middleware-next") === "1") {
529
555
  let request;
530
556
  const decoded = decodeOverriddenRequestHeaders(res.headers);
531
557
  if ([...decoded.keys()].length > 0) {
@@ -540,7 +566,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
540
566
  cookies: cookieItemsFromHeaders(res.headers)
541
567
  };
542
568
  }
543
- const rewriteHeader = res.headers.get("x-middleware-rewrite");
569
+ const rewriteHeader = res instanceof import_server.NextResponse ? res.headers.get("x-middleware-rewrite") : null;
544
570
  if (rewriteHeader && (res.status === 200 || !res.status)) {
545
571
  let request;
546
572
  const decoded = decodeOverriddenRequestHeaders(res.headers);
@@ -590,9 +616,9 @@ var RuleTimeoutError = class extends Error {
590
616
  }
591
617
  };
592
618
  function assertFiniteRuleTimeoutMs(ruleTimeoutMs) {
593
- if (ruleTimeoutMs != null && !Number.isFinite(ruleTimeoutMs)) {
619
+ if (ruleTimeoutMs != null && (!Number.isFinite(ruleTimeoutMs) || ruleTimeoutMs < 0)) {
594
620
  throw new RangeError(
595
- `[proxy-chain] ruleTimeoutMs must be a finite positive number, got ${ruleTimeoutMs}`
621
+ `[proxy-chain] ruleTimeoutMs must be a finite number >= 0 (0 disables), got ${ruleTimeoutMs}`
596
622
  );
597
623
  }
598
624
  }
@@ -613,6 +639,18 @@ async function withRuleTimeout(promise, timeoutMs, ruleName) {
613
639
  }
614
640
 
615
641
  // src/core/engine.ts
642
+ function isNextResponse(value) {
643
+ return value instanceof import_server2.NextResponse && value.headers.get("x-middleware-next") === "1";
644
+ }
645
+ function stripRoutingOverrides(res) {
646
+ const plain = !(res instanceof import_server2.NextResponse);
647
+ for (const key of [...res.headers.keys()]) {
648
+ const lower = key.toLowerCase();
649
+ if (lower === "x-middleware-override-headers" || lower.startsWith("x-middleware-request-") || plain && (lower === "x-middleware-next" || lower === "x-middleware-rewrite")) {
650
+ res.headers.delete(key);
651
+ }
652
+ }
653
+ }
616
654
  function isPathFilter(value) {
617
655
  if (value === null || typeof value !== "object") return false;
618
656
  if ("nextUrl" in value) return false;
@@ -713,6 +751,58 @@ function proxyChain(optionsOrEntries, maybeEntries) {
713
751
  appliedRequestOverrides.set(k, v);
714
752
  });
715
753
  };
754
+ const recoverRuleError = async (err, i, label, req2, startedAt) => {
755
+ if (!config.onError) {
756
+ logger.error({ rule: label, err }, "rule threw");
757
+ return { response: safeInternalError() };
758
+ }
759
+ try {
760
+ const recovered = await config.onError(err, i, req2, ctx);
761
+ if (recovered == null) return { response: safeInternalError() };
762
+ if (isNextResult(recovered) || isNextResponse(recovered)) return { raw: recovered };
763
+ if (!(recovered instanceof Response)) return { response: safeInternalError() };
764
+ stripRoutingOverrides(recovered);
765
+ headerWrites.push({
766
+ ruleIndex: i,
767
+ ruleName: label,
768
+ items: responseHeaderItems(recovered.headers)
769
+ });
770
+ cookieWrites.push({
771
+ ruleIndex: i,
772
+ ruleName: label,
773
+ items: cookieItemsFromHeaders(recovered.headers)
774
+ });
775
+ if (debug) {
776
+ logger.debug(
777
+ formatPipelineLine({
778
+ method,
779
+ path: pathname,
780
+ name: label,
781
+ traceId,
782
+ outcome: {
783
+ kind: "stop",
784
+ duration: performance.now() - startedAt,
785
+ status: recovered.status
786
+ }
787
+ })
788
+ );
789
+ }
790
+ return {
791
+ response: finalizeResponse(
792
+ recovered,
793
+ headerWrites,
794
+ cookieWrites,
795
+ headerMergeStrategy,
796
+ cookieMergeStrategy,
797
+ logger,
798
+ debug
799
+ )
800
+ };
801
+ } catch (onErrorErr) {
802
+ logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
803
+ return { response: safeInternalError() };
804
+ }
805
+ };
716
806
  try {
717
807
  for (let i = 0; i < rules.length; i++) {
718
808
  const rule = rules[i];
@@ -721,7 +811,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
721
811
  const reqHost = normalizeHost(
722
812
  activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
723
813
  );
724
- if (!ruleMatches(activeReq.nextUrl.pathname, reqHost, rule)) continue;
814
+ const matchPath = canonicalPathname(activeReq.nextUrl.pathname);
815
+ if (matchPath === null) {
816
+ return new import_server2.NextResponse("Bad Request", {
817
+ status: 400,
818
+ headers: { "content-type": "text/plain; charset=utf-8" }
819
+ });
820
+ }
821
+ if (!ruleMatches(matchPath, reqHost, rule)) continue;
725
822
  const startedAt = debug ? performance.now() : 0;
726
823
  let raw;
727
824
  try {
@@ -731,60 +828,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
731
828
  label
732
829
  );
733
830
  } 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
- }
831
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
832
+ if ("response" in recovered) return recovered.response;
833
+ raw = recovered.raw;
834
+ }
835
+ let outcome;
836
+ try {
837
+ outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
838
+ } catch (err) {
839
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
840
+ if ("response" in recovered) return recovered.response;
841
+ outcome = resolveRuleResult(recovered.raw, requestHeaderPolicy, logger, debug);
786
842
  }
787
- const outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
788
843
  const duration = debug ? performance.now() - startedAt : 0;
789
844
  if (outcome.kind === "continue") {
790
845
  if (outcome.rewriteUrl) {
@@ -819,6 +874,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
819
874
  }
820
875
  continue;
821
876
  }
877
+ stripRoutingOverrides(outcome.response);
822
878
  headerWrites.push({
823
879
  ruleIndex: i,
824
880
  ruleName: label,
@@ -900,7 +956,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
900
956
  if (config.onError) {
901
957
  try {
902
958
  const recovered = await config.onError(err, -1, materializeRequest(), ctx);
903
- if (recovered instanceof Response) return recovered;
959
+ if (recovered instanceof Response && !isNextResponse(recovered)) {
960
+ stripRoutingOverrides(recovered);
961
+ return finalizeResponse(
962
+ recovered,
963
+ headerWrites,
964
+ cookieWrites,
965
+ headerMergeStrategy,
966
+ cookieMergeStrategy,
967
+ logger,
968
+ debug
969
+ );
970
+ }
904
971
  } catch {
905
972
  }
906
973
  }
package/dist/index.js CHANGED
@@ -270,7 +270,12 @@ function isScopeObject(value) {
270
270
  return "host" in value || "path" in value;
271
271
  }
272
272
  function segmentToRegex(segment) {
273
- if (segment === "**") return "(?:.*)";
273
+ if (segment.includes("*") && segment !== "*" && segment !== "**") {
274
+ throw new Error(
275
+ `[proxy-chain] path segment "${segment}" mixes a wildcard with other characters. Use a whole-segment * or **.`
276
+ );
277
+ }
278
+ if (segment === "**") return "(?:[\\s\\S]*)";
274
279
  if (segment === "*") return "[^/]+";
275
280
  if (segment.startsWith(":")) return "[^/]+";
276
281
  return escapeRegex(segment);
@@ -290,7 +295,7 @@ function compileRegexPath(pattern) {
290
295
  const wrapFull = !hasStart && !hasEnd;
291
296
  const start = hasStart || wrapFull ? "^" : "";
292
297
  const end = hasEnd || wrapFull ? "$" : "";
293
- return toStatelessRegExp(new RegExp(`${start}${source}${end}`, pattern.flags));
298
+ return toStatelessRegExp(new RegExp(`${start}(?:${source})${end}`, pattern.flags));
294
299
  }
295
300
  function compileStringPath(pattern) {
296
301
  const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
@@ -306,7 +311,7 @@ function compileStringPath(pattern) {
306
311
  pathPattern = prefix ? `/${prefix}/[^/]+` : `/[^/]+`;
307
312
  } else if (trailingGlobstar) {
308
313
  const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
309
- pathPattern = prefix ? `/${prefix}(?:/.*)?` : `/(?:.*)?`;
314
+ pathPattern = prefix ? `/${prefix}(?:/[\\s\\S]*)?` : `/(?:[\\s\\S]*)?`;
310
315
  } else {
311
316
  pathPattern = `/${segments.map(segmentToRegex).join("/")}`;
312
317
  }
@@ -363,10 +368,17 @@ function toRule(entry) {
363
368
  const rule = entry;
364
369
  const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
365
370
  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
- }));
371
+ const harden = (scopes) => scopes?.map((s) => {
372
+ if (!s.host && !s.path) {
373
+ throw new Error(
374
+ "[proxy-chain] include/exclude scope needs `host` or `path`. Build scopes with path() or host()."
375
+ );
376
+ }
377
+ return {
378
+ host: s.host ? toStatelessRegExp(s.host) : void 0,
379
+ path: s.path ? toStatelessRegExp(s.path) : void 0
380
+ };
381
+ });
370
382
  return {
371
383
  ...rule,
372
384
  name: name ?? void 0,
@@ -401,9 +413,18 @@ function normalizeHost(raw) {
401
413
  const end = first.indexOf("]");
402
414
  return end === -1 ? first : first.slice(1, end);
403
415
  }
404
- const withoutPort = first.replace(/:\d+$/, "");
416
+ const withoutPort = first.replace(/:\d+$/, "").replace(/\.$/, "");
405
417
  return withoutPort || null;
406
418
  }
419
+ function canonicalPathname(pathname) {
420
+ let decoded;
421
+ try {
422
+ decoded = decodeURIComponent(pathname);
423
+ } catch {
424
+ return null;
425
+ }
426
+ return decoded.length > 1 ? decoded.replace(/\/+$/, "") || "/" : decoded;
427
+ }
407
428
  function scopeKey(scope) {
408
429
  return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
409
430
  }
@@ -470,6 +491,11 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
470
491
  if (res == null) {
471
492
  return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
472
493
  }
494
+ if (!isNextResult(res) && !(res instanceof Response)) {
495
+ throw new TypeError(
496
+ `[proxy-chain] rule must return next(), a Response, or undefined. Got ${typeof res}.`
497
+ );
498
+ }
473
499
  if (isNextResult(res)) {
474
500
  let request;
475
501
  if (res.request) {
@@ -492,7 +518,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
492
518
  cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
493
519
  };
494
520
  }
495
- if (res.headers.get("x-middleware-next") === "1") {
521
+ if (res instanceof NextResponse && res.headers.get("x-middleware-next") === "1") {
496
522
  let request;
497
523
  const decoded = decodeOverriddenRequestHeaders(res.headers);
498
524
  if ([...decoded.keys()].length > 0) {
@@ -507,7 +533,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
507
533
  cookies: cookieItemsFromHeaders(res.headers)
508
534
  };
509
535
  }
510
- const rewriteHeader = res.headers.get("x-middleware-rewrite");
536
+ const rewriteHeader = res instanceof NextResponse ? res.headers.get("x-middleware-rewrite") : null;
511
537
  if (rewriteHeader && (res.status === 200 || !res.status)) {
512
538
  let request;
513
539
  const decoded = decodeOverriddenRequestHeaders(res.headers);
@@ -557,9 +583,9 @@ var RuleTimeoutError = class extends Error {
557
583
  }
558
584
  };
559
585
  function assertFiniteRuleTimeoutMs(ruleTimeoutMs) {
560
- if (ruleTimeoutMs != null && !Number.isFinite(ruleTimeoutMs)) {
586
+ if (ruleTimeoutMs != null && (!Number.isFinite(ruleTimeoutMs) || ruleTimeoutMs < 0)) {
561
587
  throw new RangeError(
562
- `[proxy-chain] ruleTimeoutMs must be a finite positive number, got ${ruleTimeoutMs}`
588
+ `[proxy-chain] ruleTimeoutMs must be a finite number >= 0 (0 disables), got ${ruleTimeoutMs}`
563
589
  );
564
590
  }
565
591
  }
@@ -580,6 +606,18 @@ async function withRuleTimeout(promise, timeoutMs, ruleName) {
580
606
  }
581
607
 
582
608
  // src/core/engine.ts
609
+ function isNextResponse(value) {
610
+ return value instanceof NextResponse2 && value.headers.get("x-middleware-next") === "1";
611
+ }
612
+ function stripRoutingOverrides(res) {
613
+ const plain = !(res instanceof NextResponse2);
614
+ for (const key of [...res.headers.keys()]) {
615
+ const lower = key.toLowerCase();
616
+ if (lower === "x-middleware-override-headers" || lower.startsWith("x-middleware-request-") || plain && (lower === "x-middleware-next" || lower === "x-middleware-rewrite")) {
617
+ res.headers.delete(key);
618
+ }
619
+ }
620
+ }
583
621
  function isPathFilter(value) {
584
622
  if (value === null || typeof value !== "object") return false;
585
623
  if ("nextUrl" in value) return false;
@@ -680,6 +718,58 @@ function proxyChain(optionsOrEntries, maybeEntries) {
680
718
  appliedRequestOverrides.set(k, v);
681
719
  });
682
720
  };
721
+ const recoverRuleError = async (err, i, label, req2, startedAt) => {
722
+ if (!config.onError) {
723
+ logger.error({ rule: label, err }, "rule threw");
724
+ return { response: safeInternalError() };
725
+ }
726
+ try {
727
+ const recovered = await config.onError(err, i, req2, ctx);
728
+ if (recovered == null) return { response: safeInternalError() };
729
+ if (isNextResult(recovered) || isNextResponse(recovered)) return { raw: recovered };
730
+ if (!(recovered instanceof Response)) return { response: safeInternalError() };
731
+ stripRoutingOverrides(recovered);
732
+ headerWrites.push({
733
+ ruleIndex: i,
734
+ ruleName: label,
735
+ items: responseHeaderItems(recovered.headers)
736
+ });
737
+ cookieWrites.push({
738
+ ruleIndex: i,
739
+ ruleName: label,
740
+ items: cookieItemsFromHeaders(recovered.headers)
741
+ });
742
+ if (debug) {
743
+ logger.debug(
744
+ formatPipelineLine({
745
+ method,
746
+ path: pathname,
747
+ name: label,
748
+ traceId,
749
+ outcome: {
750
+ kind: "stop",
751
+ duration: performance.now() - startedAt,
752
+ status: recovered.status
753
+ }
754
+ })
755
+ );
756
+ }
757
+ return {
758
+ response: finalizeResponse(
759
+ recovered,
760
+ headerWrites,
761
+ cookieWrites,
762
+ headerMergeStrategy,
763
+ cookieMergeStrategy,
764
+ logger,
765
+ debug
766
+ )
767
+ };
768
+ } catch (onErrorErr) {
769
+ logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
770
+ return { response: safeInternalError() };
771
+ }
772
+ };
683
773
  try {
684
774
  for (let i = 0; i < rules.length; i++) {
685
775
  const rule = rules[i];
@@ -688,7 +778,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
688
778
  const reqHost = normalizeHost(
689
779
  activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
690
780
  );
691
- if (!ruleMatches(activeReq.nextUrl.pathname, reqHost, rule)) continue;
781
+ const matchPath = canonicalPathname(activeReq.nextUrl.pathname);
782
+ if (matchPath === null) {
783
+ return new NextResponse2("Bad Request", {
784
+ status: 400,
785
+ headers: { "content-type": "text/plain; charset=utf-8" }
786
+ });
787
+ }
788
+ if (!ruleMatches(matchPath, reqHost, rule)) continue;
692
789
  const startedAt = debug ? performance.now() : 0;
693
790
  let raw;
694
791
  try {
@@ -698,60 +795,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
698
795
  label
699
796
  );
700
797
  } 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
- }
798
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
799
+ if ("response" in recovered) return recovered.response;
800
+ raw = recovered.raw;
801
+ }
802
+ let outcome;
803
+ try {
804
+ outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
805
+ } catch (err) {
806
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
807
+ if ("response" in recovered) return recovered.response;
808
+ outcome = resolveRuleResult(recovered.raw, requestHeaderPolicy, logger, debug);
753
809
  }
754
- const outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
755
810
  const duration = debug ? performance.now() - startedAt : 0;
756
811
  if (outcome.kind === "continue") {
757
812
  if (outcome.rewriteUrl) {
@@ -786,6 +841,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
786
841
  }
787
842
  continue;
788
843
  }
844
+ stripRoutingOverrides(outcome.response);
789
845
  headerWrites.push({
790
846
  ruleIndex: i,
791
847
  ruleName: label,
@@ -867,7 +923,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
867
923
  if (config.onError) {
868
924
  try {
869
925
  const recovered = await config.onError(err, -1, materializeRequest(), ctx);
870
- if (recovered instanceof Response) return recovered;
926
+ if (recovered instanceof Response && !isNextResponse(recovered)) {
927
+ stripRoutingOverrides(recovered);
928
+ return finalizeResponse(
929
+ recovered,
930
+ headerWrites,
931
+ cookieWrites,
932
+ headerMergeStrategy,
933
+ cookieMergeStrategy,
934
+ logger,
935
+ debug
936
+ );
937
+ }
871
938
  } catch {
872
939
  }
873
940
  }
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.6",
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"