@klnap/next-proxy-chain 1.0.4 → 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 +36 -2
- package/LICENSE +1 -1
- package/README.md +49 -202
- package/dist/index.cjs +157 -88
- package/dist/index.d.cts +22 -22
- package/dist/index.d.ts +22 -22
- package/dist/index.js +157 -88
- package/package.json +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,41 @@ 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
|
-
## [
|
|
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.
|
|
35
|
+
|
|
36
|
+
## [1.0.5] - 2026-10-29
|
|
37
|
+
|
|
38
|
+
### Changed
|
|
39
|
+
|
|
40
|
+
- Host folder prefix rewrite logic lives in a dedicated module with unit coverage; runtime behavior is unchanged.
|
|
41
|
+
- README lists peer requirements and trims redundant install/badge copy.
|
|
8
42
|
|
|
9
43
|
## [1.0.4] - 2026-08-27
|
|
10
44
|
|
|
@@ -34,7 +68,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
34
68
|
|
|
35
69
|
- `headerMergeStrategy` applies only to **response** headers. Request overrides stay last-write-wins.
|
|
36
70
|
- Package metadata: `repository`, `bugs`, `homepage`.
|
|
37
|
-
- Tests run on `bun:test`; removed Typedoc site
|
|
71
|
+
- Tests run on `bun:test`; removed Typedoc site from the package repo.
|
|
38
72
|
|
|
39
73
|
## [1.0.3] - 2026-08-26
|
|
40
74
|
|
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -1,240 +1,87 @@
|
|
|
1
1
|
# @klnap/next-proxy-chain
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Compose independent request rules for Next.js `proxy.ts` (or `middleware.ts`) without writing one long function.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
[](https://www.npmjs.com/package/@klnap/next-proxy-chain)
|
|
7
|
-
[](https://github.com/klnap/next-proxy-chain/blob/main/LICENSE)
|
|
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.
|
|
8
6
|
|
|
9
|
-
|
|
7
|
+
```ts
|
|
8
|
+
import { defineProxy, next, path, proxyChain } from '@klnap/next-proxy-chain'
|
|
9
|
+
import { NextResponse } from 'next/server'
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
const securityHeaders = defineProxy('security-headers', () =>
|
|
12
|
+
next({ headers: { 'x-frame-options': 'DENY' } })
|
|
13
|
+
)
|
|
12
14
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
- **Deterministic Header & Cookie Merging**: Propagate request header overrides downstream, deduplicate `Set-Cookie` headers, and merge response headers with configurable conflict strategies.
|
|
17
|
-
- **Route & Host Scoping**: Declarative path matching (globs, parameters, regex) and host filtering with `include` and `exclude` rules.
|
|
18
|
-
- **Safe Pattern Matching**: Normalizes stateful regular expressions to avoid `lastIndex`-related matching issues.
|
|
19
|
-
- **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).
|
|
20
|
-
- **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.
|
|
21
|
-
- **Zero Runtime Dependencies**: Fully typed in TypeScript with no runtime dependencies (`next` is a peer).
|
|
22
|
-
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
## Installation
|
|
26
|
-
|
|
27
|
-
```bash
|
|
28
|
-
npm install @klnap/next-proxy-chain
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
Or with your preferred package manager:
|
|
32
|
-
|
|
33
|
-
```bash
|
|
34
|
-
pnpm add @klnap/next-proxy-chain
|
|
35
|
-
# or
|
|
36
|
-
bun add @klnap/next-proxy-chain
|
|
37
|
-
# or
|
|
38
|
-
yarn add @klnap/next-proxy-chain
|
|
39
|
-
```
|
|
40
|
-
|
|
41
|
-
---
|
|
42
|
-
|
|
43
|
-
## Quick Start
|
|
44
|
-
|
|
45
|
-
```typescript
|
|
46
|
-
// proxy.ts or middleware.ts
|
|
47
|
-
import { defineProxy, next, path, proxyChain } from "@klnap/next-proxy-chain"
|
|
48
|
-
import { NextResponse } from "next/server"
|
|
49
|
-
|
|
50
|
-
const auth = defineProxy("auth", (req, ctx) => {
|
|
51
|
-
const token = req.cookies.get("session")?.value
|
|
52
|
-
if (!token) {
|
|
53
|
-
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))
|
|
54
18
|
}
|
|
55
|
-
ctx.set("userId", "usr_123")
|
|
56
19
|
return next()
|
|
57
20
|
})
|
|
58
21
|
|
|
59
|
-
|
|
60
|
-
return next({
|
|
61
|
-
headers: { "x-frame-options": "DENY" },
|
|
62
|
-
})
|
|
63
|
-
})
|
|
64
|
-
|
|
65
|
-
export default proxyChain({ debug: process.env.NODE_ENV !== "production" }, [
|
|
66
|
-
auth({ include: path("/dashboard/*") }),
|
|
67
|
-
security,
|
|
68
|
-
])
|
|
22
|
+
export default proxyChain([securityHeaders, requireSession({ include: path('/dashboard/**') })])
|
|
69
23
|
|
|
70
24
|
export const config = {
|
|
71
|
-
matcher: [
|
|
25
|
+
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
|
|
72
26
|
}
|
|
73
27
|
```
|
|
74
28
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
## Routing & Scoping
|
|
78
|
-
|
|
79
|
-
Scope rules to specific paths, hosts, or combinations using `defineProxy`:
|
|
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.
|
|
80
30
|
|
|
81
|
-
|
|
82
|
-
import { defineProxy, host, next, path } from "@klnap/next-proxy-chain"
|
|
31
|
+
## Install
|
|
83
32
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
// Scoped rule configuration
|
|
90
|
-
const scopedRule = apiAuth({
|
|
91
|
-
include: path("/api/*"),
|
|
92
|
-
exclude: path("/api/public/*"),
|
|
93
|
-
})
|
|
94
|
-
|
|
95
|
-
// Combined path and host filter
|
|
96
|
-
const adminRule = apiAuth({
|
|
97
|
-
include: {
|
|
98
|
-
host: host("admin.example.com"),
|
|
99
|
-
path: path("/settings/**"),
|
|
100
|
-
},
|
|
101
|
-
})
|
|
33
|
+
```sh
|
|
34
|
+
npm install @klnap/next-proxy-chain
|
|
35
|
+
# or
|
|
36
|
+
bun add @klnap/next-proxy-chain
|
|
102
37
|
```
|
|
103
38
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
- `path("/api/*")` — exactly one segment (`/api/users` yes, `/api/users/123` no)
|
|
107
|
-
- `path("/docs/**")` — the prefix plus zero or more extra segments (`/docs`, `/docs/a/b`)
|
|
108
|
-
- `path("/users/:id")` — one segment (no capture groups; matching only)
|
|
109
|
-
- `path(/^\/foo$/)` — user anchors are kept (`/foo` yes, `/x/foo` no)
|
|
110
|
-
|
|
111
|
-
### Host Patterns
|
|
112
|
-
|
|
113
|
-
- `host("admin.example.com")` — exact hostname (case-insensitive, port stripped at match time)
|
|
114
|
-
- `host("*.example.com")` — one DNS label (`foo.example.com` yes, `example.com` no, `a.b.example.com` no)
|
|
115
|
-
- `host(/shop\.localhost$/)` — raw RegExp
|
|
39
|
+
`next` is a peer dependency (`>=15.0.0`). The package has no runtime dependencies.
|
|
116
40
|
|
|
117
|
-
|
|
41
|
+
## When to use it
|
|
118
42
|
|
|
119
|
-
|
|
43
|
+
Use it when one Proxy file needs several independent concerns, for example:
|
|
120
44
|
|
|
121
|
-
|
|
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.
|
|
122
50
|
|
|
123
|
-
|
|
51
|
+
A single redirect rule does not need it. Write `NextResponse.redirect` directly in `proxy.ts`.
|
|
124
52
|
|
|
125
|
-
|
|
126
|
-
type Ctx = { user?: { id: string; role: string } }
|
|
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.
|
|
127
54
|
|
|
128
|
-
|
|
129
|
-
ctx.user = { id: "usr_1", role: "admin" }
|
|
130
|
-
return next()
|
|
131
|
-
})
|
|
55
|
+
## How it works
|
|
132
56
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
})
|
|
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.
|
|
139
62
|
|
|
140
|
-
|
|
141
|
-
```
|
|
63
|
+
[Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md) explains the execution model in full.
|
|
142
64
|
|
|
143
|
-
|
|
65
|
+
## Documentation
|
|
144
66
|
|
|
145
|
-
|
|
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.
|
|
146
71
|
|
|
147
|
-
|
|
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.
|
|
148
73
|
|
|
149
|
-
|
|
150
|
-
return next({
|
|
151
|
-
// Downstream request headers (NextRequest & server components). Always last-write-wins.
|
|
152
|
-
request: {
|
|
153
|
-
"x-user-id": "usr_123",
|
|
154
|
-
},
|
|
155
|
-
// Final outgoing response headers / Set-Cookie
|
|
156
|
-
headers: {
|
|
157
|
-
"cache-control": "no-store",
|
|
158
|
-
"set-cookie": "session=abc; Path=/",
|
|
159
|
-
},
|
|
160
|
-
})
|
|
161
|
-
```
|
|
74
|
+
## Compatibility
|
|
162
75
|
|
|
163
|
-
-
|
|
164
|
-
-
|
|
165
|
-
-
|
|
166
|
-
- Custom merge `return null` removes that response header from the final `Response`.
|
|
167
|
-
|
|
168
|
-
---
|
|
169
|
-
|
|
170
|
-
## API Reference
|
|
171
|
-
|
|
172
|
-
### Core Functions
|
|
173
|
-
|
|
174
|
-
| Function | Signature | Description |
|
|
175
|
-
| :--- | :--- | :--- |
|
|
176
|
-
| `proxyChain(rules)` | `(rules: Entry[]) => Handler` | Creates a middleware/proxy handler from a list of rules. |
|
|
177
|
-
| `proxyChain(options, rules)` | `(options: ProxyChainOptions, rules: Entry[]) => Handler` | Creates a handler with custom pipeline options. |
|
|
178
|
-
| `defineProxy(name?, fn)` | `(name?: string, fn: ProxyFn) => DefinedProxy` | Defines a reusable proxy rule with scoping capabilities. |
|
|
179
|
-
| `next(options?)` | `(options?: NextOptions) => NextResult` | Returns a continuation token with optional header mutations. |
|
|
180
|
-
| `path(pattern)` | `(pattern: string \| RegExp) => RegExp` | Compiles a path pattern into a stateless `RegExp`. |
|
|
181
|
-
| `host(matcher)` | `(matcher: HostMatcher) => RegExp` | Compiles hostname(s) into an anchored `RegExp` (`*` = one DNS label). |
|
|
182
|
-
| `createProxyContext()` | `() => ProxyContext` | Creates a new `Map<string, unknown>` context instance. |
|
|
183
|
-
| `isNextResult(value)` | `(value: unknown) => boolean` | Type guard for `next()` continuation tokens. |
|
|
184
|
-
| `RuleTimeoutError` | `Error` | Thrown internally when `ruleTimeoutMs` is exceeded (catchable in `onError`). |
|
|
185
|
-
|
|
186
|
-
### Configuration Options (`ProxyChainOptions`)
|
|
187
|
-
|
|
188
|
-
| Option | Type | Default | Description |
|
|
189
|
-
| :--- | :--- | :--- | :--- |
|
|
190
|
-
| `createContext` | `(req, event) => TContext` | `() => new Map()` | Factory for custom per-request context. Required for a non-`Map` `TContext`. |
|
|
191
|
-
| `headerMergeStrategy` | `"last-write-wins" \| "first-write-wins" \| Function` | `"last-write-wins"` | Conflict strategy for **response** headers only. |
|
|
192
|
-
| `cookieMergeStrategy` | `"last-write-wins" \| "first-write-wins" \| Function` | `"last-write-wins"` | Conflict strategy for `Set-Cookie` (same name+domain+path). |
|
|
193
|
-
| `ruleTimeoutMs` | `number` | `0` | Wall-clock timeout per rule in ms (`0` disables). Does not abort the rule function; leftover rejections are swallowed. |
|
|
194
|
-
| `onError` | `(err, index, req, ctx) => Response \| NextResult \| void` | `undefined` | Recovery hook. See **Errors** below. |
|
|
195
|
-
| `requestHeaderPolicy` | `{ blocked?: string[], allowed?: string[] }` | `{}` | Blocklist/allowlist for **request** header mutations. |
|
|
196
|
-
| `debug` | `boolean` | `false` | Structured one-line logs per rule. |
|
|
197
|
-
| `logger` | `ChainLogger` | `console` | Custom logger (`debug`, `info`, `warn`, `error`). |
|
|
198
|
-
| `strictOverrideCheck` | `boolean` | `false` | Throw at init if `NextResponse.next()` request overrides look unsupported. |
|
|
199
|
-
| `hostFolderHeader` | `string` | unset | Opt-in: request header name that prefixes rewrites with a physical folder (e.g. `"x-internal-host-folder"`). Off by default. |
|
|
200
|
-
|
|
201
|
-
### Errors (`onError`)
|
|
202
|
-
|
|
203
|
-
| `onError` returns | Behavior |
|
|
204
|
-
| :--- | :--- |
|
|
205
|
-
| `Response` | Stop and return that response (headers/cookies still merged). |
|
|
206
|
-
| `next()` | Continue to the next rule (rule-level errors only). |
|
|
207
|
-
| `undefined` / `void` / `null` | **Fail closed** — `500 Internal Server Error`. |
|
|
208
|
-
| throws | `500 Internal Server Error`. |
|
|
209
|
-
| omitted | Rule throw → `500`. |
|
|
210
|
-
|
|
211
|
-
`ruleIndex` is `0`-based. `-1` means an engine-level error after context creation; only a `Response` is honored (the pipeline cannot continue).
|
|
212
|
-
|
|
213
|
-
A logging-only `onError: (err) => { console.error(err) }` does **not** skip the failure.
|
|
214
|
-
|
|
215
|
-
### Return Value Protocol
|
|
216
|
-
|
|
217
|
-
A rule (`ProxyFn`) can return:
|
|
218
|
-
|
|
219
|
-
| Return Value | Behavior |
|
|
220
|
-
| :--- | :--- |
|
|
221
|
-
| `next({ request?, headers? })` | Continues. Queues request overrides, response headers, and `Set-Cookie`. |
|
|
222
|
-
| `undefined` / `void` | Continues without mutations. |
|
|
223
|
-
| `NextResponse.next()` | Continues; extracts Next.js request override headers and cookies. |
|
|
224
|
-
| `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. |
|
|
225
|
-
| `NextResponse.redirect(url)` | Stops immediately with the redirect. |
|
|
226
|
-
| `Response` / `NextResponse.json()` | Stops immediately with that response. |
|
|
227
|
-
|
|
228
|
-
---
|
|
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.
|
|
229
79
|
|
|
230
80
|
## Links
|
|
231
81
|
|
|
232
|
-
- [
|
|
233
|
-
- [
|
|
234
|
-
|
|
235
|
-
---
|
|
82
|
+
- [Changelog](https://github.com/klnap/next-proxy-chain/blob/main/CHANGELOG.md)
|
|
83
|
+
- [Issues](https://github.com/klnap/next-proxy-chain/issues)
|
|
236
84
|
|
|
237
85
|
## License
|
|
238
86
|
|
|
239
|
-
[MIT](
|
|
240
|
-
|
|
87
|
+
[MIT](https://github.com/klnap/next-proxy-chain/blob/main/LICENSE)
|
package/dist/index.cjs
CHANGED
|
@@ -31,9 +31,6 @@ __export(index_exports, {
|
|
|
31
31
|
});
|
|
32
32
|
module.exports = __toCommonJS(index_exports);
|
|
33
33
|
|
|
34
|
-
// src/core/engine.ts
|
|
35
|
-
var import_server2 = require("next/server");
|
|
36
|
-
|
|
37
34
|
// src/core/constants.ts
|
|
38
35
|
var NEXT = /* @__PURE__ */ Symbol.for("proxy-chain.next");
|
|
39
36
|
var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
|
|
@@ -70,6 +67,9 @@ function createProxyContext() {
|
|
|
70
67
|
return /* @__PURE__ */ new Map();
|
|
71
68
|
}
|
|
72
69
|
|
|
70
|
+
// src/core/engine.ts
|
|
71
|
+
var import_server2 = require("next/server");
|
|
72
|
+
|
|
73
73
|
// src/core/headers.ts
|
|
74
74
|
function normalizeHeaderName(name) {
|
|
75
75
|
return name.toLowerCase();
|
|
@@ -212,6 +212,26 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
|
|
|
212
212
|
}
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
+
// src/core/host-folder-prefix.ts
|
|
216
|
+
function physicalFolderPrefix(raw) {
|
|
217
|
+
return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
|
|
218
|
+
}
|
|
219
|
+
function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
|
|
220
|
+
try {
|
|
221
|
+
const parsed = new URL(rewriteUrl, baseUrl);
|
|
222
|
+
if (!parsed.pathname.startsWith(folder)) {
|
|
223
|
+
parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
|
|
224
|
+
return parsed.toString();
|
|
225
|
+
}
|
|
226
|
+
return rewriteUrl;
|
|
227
|
+
} catch {
|
|
228
|
+
if (!rewriteUrl.startsWith(folder)) {
|
|
229
|
+
return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
|
|
230
|
+
}
|
|
231
|
+
return rewriteUrl;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
215
235
|
// src/core/logger.ts
|
|
216
236
|
var LEVEL_RANK = {
|
|
217
237
|
debug: 10,
|
|
@@ -283,7 +303,12 @@ function isScopeObject(value) {
|
|
|
283
303
|
return "host" in value || "path" in value;
|
|
284
304
|
}
|
|
285
305
|
function segmentToRegex(segment) {
|
|
286
|
-
if (segment
|
|
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]*)";
|
|
287
312
|
if (segment === "*") return "[^/]+";
|
|
288
313
|
if (segment.startsWith(":")) return "[^/]+";
|
|
289
314
|
return escapeRegex(segment);
|
|
@@ -303,7 +328,7 @@ function compileRegexPath(pattern) {
|
|
|
303
328
|
const wrapFull = !hasStart && !hasEnd;
|
|
304
329
|
const start = hasStart || wrapFull ? "^" : "";
|
|
305
330
|
const end = hasEnd || wrapFull ? "$" : "";
|
|
306
|
-
return toStatelessRegExp(new RegExp(`${start}
|
|
331
|
+
return toStatelessRegExp(new RegExp(`${start}(?:${source})${end}`, pattern.flags));
|
|
307
332
|
}
|
|
308
333
|
function compileStringPath(pattern) {
|
|
309
334
|
const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
|
|
@@ -319,7 +344,7 @@ function compileStringPath(pattern) {
|
|
|
319
344
|
pathPattern = prefix ? `/${prefix}/[^/]+` : `/[^/]+`;
|
|
320
345
|
} else if (trailingGlobstar) {
|
|
321
346
|
const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
|
|
322
|
-
pathPattern = prefix ? `/${prefix}(
|
|
347
|
+
pathPattern = prefix ? `/${prefix}(?:/[\\s\\S]*)?` : `/(?:[\\s\\S]*)?`;
|
|
323
348
|
} else {
|
|
324
349
|
pathPattern = `/${segments.map(segmentToRegex).join("/")}`;
|
|
325
350
|
}
|
|
@@ -376,10 +401,17 @@ function toRule(entry) {
|
|
|
376
401
|
const rule = entry;
|
|
377
402
|
const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
|
|
378
403
|
const name = extractMeaningfulName(rule.name) ?? runName;
|
|
379
|
-
const harden = (scopes) => scopes?.map((s) =>
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
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
|
+
});
|
|
383
415
|
return {
|
|
384
416
|
...rule,
|
|
385
417
|
name: name ?? void 0,
|
|
@@ -414,9 +446,18 @@ function normalizeHost(raw) {
|
|
|
414
446
|
const end = first.indexOf("]");
|
|
415
447
|
return end === -1 ? first : first.slice(1, end);
|
|
416
448
|
}
|
|
417
|
-
const withoutPort = first.replace(/:\d+$/, "");
|
|
449
|
+
const withoutPort = first.replace(/:\d+$/, "").replace(/\.$/, "");
|
|
418
450
|
return withoutPort || null;
|
|
419
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
|
+
}
|
|
420
461
|
function scopeKey(scope) {
|
|
421
462
|
return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
|
|
422
463
|
}
|
|
@@ -483,6 +524,11 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
483
524
|
if (res == null) {
|
|
484
525
|
return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
|
|
485
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
|
+
}
|
|
486
532
|
if (isNextResult(res)) {
|
|
487
533
|
let request;
|
|
488
534
|
if (res.request) {
|
|
@@ -505,7 +551,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
505
551
|
cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
|
|
506
552
|
};
|
|
507
553
|
}
|
|
508
|
-
if (res.headers.get("x-middleware-next") === "1") {
|
|
554
|
+
if (res instanceof import_server.NextResponse && res.headers.get("x-middleware-next") === "1") {
|
|
509
555
|
let request;
|
|
510
556
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
511
557
|
if ([...decoded.keys()].length > 0) {
|
|
@@ -520,7 +566,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
520
566
|
cookies: cookieItemsFromHeaders(res.headers)
|
|
521
567
|
};
|
|
522
568
|
}
|
|
523
|
-
const rewriteHeader = res.headers.get("x-middleware-rewrite");
|
|
569
|
+
const rewriteHeader = res instanceof import_server.NextResponse ? res.headers.get("x-middleware-rewrite") : null;
|
|
524
570
|
if (rewriteHeader && (res.status === 200 || !res.status)) {
|
|
525
571
|
let request;
|
|
526
572
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
@@ -570,9 +616,9 @@ var RuleTimeoutError = class extends Error {
|
|
|
570
616
|
}
|
|
571
617
|
};
|
|
572
618
|
function assertFiniteRuleTimeoutMs(ruleTimeoutMs) {
|
|
573
|
-
if (ruleTimeoutMs != null && !Number.isFinite(ruleTimeoutMs)) {
|
|
619
|
+
if (ruleTimeoutMs != null && (!Number.isFinite(ruleTimeoutMs) || ruleTimeoutMs < 0)) {
|
|
574
620
|
throw new RangeError(
|
|
575
|
-
`[proxy-chain] ruleTimeoutMs must be a finite
|
|
621
|
+
`[proxy-chain] ruleTimeoutMs must be a finite number >= 0 (0 disables), got ${ruleTimeoutMs}`
|
|
576
622
|
);
|
|
577
623
|
}
|
|
578
624
|
}
|
|
@@ -593,6 +639,18 @@ async function withRuleTimeout(promise, timeoutMs, ruleName) {
|
|
|
593
639
|
}
|
|
594
640
|
|
|
595
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
|
+
}
|
|
596
654
|
function isPathFilter(value) {
|
|
597
655
|
if (value === null || typeof value !== "object") return false;
|
|
598
656
|
if ("nextUrl" in value) return false;
|
|
@@ -634,24 +692,6 @@ function resolveConfig(overrides, fallbackCreateContext) {
|
|
|
634
692
|
assertFiniteRuleTimeoutMs(config.ruleTimeoutMs);
|
|
635
693
|
return config;
|
|
636
694
|
}
|
|
637
|
-
function physicalFolderPrefix(raw) {
|
|
638
|
-
return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
|
|
639
|
-
}
|
|
640
|
-
function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
|
|
641
|
-
try {
|
|
642
|
-
const parsed = new URL(rewriteUrl, baseUrl);
|
|
643
|
-
if (!parsed.pathname.startsWith(folder)) {
|
|
644
|
-
parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
|
|
645
|
-
return parsed.toString();
|
|
646
|
-
}
|
|
647
|
-
return rewriteUrl;
|
|
648
|
-
} catch {
|
|
649
|
-
if (!rewriteUrl.startsWith(folder)) {
|
|
650
|
-
return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
|
|
651
|
-
}
|
|
652
|
-
return rewriteUrl;
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
695
|
function proxyChain(optionsOrEntries, maybeEntries) {
|
|
656
696
|
const options = Array.isArray(optionsOrEntries) ? {} : optionsOrEntries;
|
|
657
697
|
const entries = (Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries) ?? [];
|
|
@@ -711,6 +751,58 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
711
751
|
appliedRequestOverrides.set(k, v);
|
|
712
752
|
});
|
|
713
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
|
+
};
|
|
714
806
|
try {
|
|
715
807
|
for (let i = 0; i < rules.length; i++) {
|
|
716
808
|
const rule = rules[i];
|
|
@@ -719,7 +811,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
719
811
|
const reqHost = normalizeHost(
|
|
720
812
|
activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
|
|
721
813
|
);
|
|
722
|
-
|
|
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;
|
|
723
822
|
const startedAt = debug ? performance.now() : 0;
|
|
724
823
|
let raw;
|
|
725
824
|
try {
|
|
@@ -729,60 +828,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
729
828
|
label
|
|
730
829
|
);
|
|
731
830
|
} catch (err) {
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
});
|
|
744
|
-
cookieWrites.push({
|
|
745
|
-
ruleIndex: i,
|
|
746
|
-
ruleName: label,
|
|
747
|
-
items: cookieItemsFromHeaders(recovered.headers)
|
|
748
|
-
});
|
|
749
|
-
if (debug) {
|
|
750
|
-
logger.debug(
|
|
751
|
-
formatPipelineLine({
|
|
752
|
-
method,
|
|
753
|
-
path: pathname,
|
|
754
|
-
name: label,
|
|
755
|
-
traceId,
|
|
756
|
-
outcome: {
|
|
757
|
-
kind: "stop",
|
|
758
|
-
duration: performance.now() - startedAt,
|
|
759
|
-
status: recovered.status
|
|
760
|
-
}
|
|
761
|
-
})
|
|
762
|
-
);
|
|
763
|
-
}
|
|
764
|
-
return finalizeResponse(
|
|
765
|
-
recovered,
|
|
766
|
-
headerWrites,
|
|
767
|
-
cookieWrites,
|
|
768
|
-
headerMergeStrategy,
|
|
769
|
-
cookieMergeStrategy,
|
|
770
|
-
logger,
|
|
771
|
-
debug
|
|
772
|
-
);
|
|
773
|
-
} else {
|
|
774
|
-
return safeInternalError();
|
|
775
|
-
}
|
|
776
|
-
} catch (onErrorErr) {
|
|
777
|
-
logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
|
|
778
|
-
return safeInternalError();
|
|
779
|
-
}
|
|
780
|
-
} else {
|
|
781
|
-
logger.error({ rule: label, err }, "rule threw");
|
|
782
|
-
return safeInternalError();
|
|
783
|
-
}
|
|
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);
|
|
784
842
|
}
|
|
785
|
-
const outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
|
|
786
843
|
const duration = debug ? performance.now() - startedAt : 0;
|
|
787
844
|
if (outcome.kind === "continue") {
|
|
788
845
|
if (outcome.rewriteUrl) {
|
|
@@ -817,6 +874,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
817
874
|
}
|
|
818
875
|
continue;
|
|
819
876
|
}
|
|
877
|
+
stripRoutingOverrides(outcome.response);
|
|
820
878
|
headerWrites.push({
|
|
821
879
|
ruleIndex: i,
|
|
822
880
|
ruleName: label,
|
|
@@ -898,7 +956,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
898
956
|
if (config.onError) {
|
|
899
957
|
try {
|
|
900
958
|
const recovered = await config.onError(err, -1, materializeRequest(), ctx);
|
|
901
|
-
if (recovered instanceof Response
|
|
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
|
+
}
|
|
902
971
|
} catch {
|
|
903
972
|
}
|
|
904
973
|
}
|
package/dist/index.d.cts
CHANGED
|
@@ -61,7 +61,7 @@ type ProxyFn<TContext = ProxyContext> = (req: NextRequest, ctx: TContext, event:
|
|
|
61
61
|
type ProxyRule<TContext = ProxyContext> = BaseProxyRule<ProxyFn<TContext>>;
|
|
62
62
|
type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>);
|
|
63
63
|
type Entry<TContext = ProxyContext> = ProxyFn<TContext> | ProxyRule<TContext>;
|
|
64
|
-
type MergeStrategy =
|
|
64
|
+
type MergeStrategy = 'last-write-wins' | 'first-write-wins' | ((key: string, existing: string, incoming: string) => string | null);
|
|
65
65
|
interface ChainLogger {
|
|
66
66
|
debug: (metaOrMsg: unknown, maybeMsg?: string) => void;
|
|
67
67
|
info: (metaOrMsg: unknown, maybeMsg?: string) => void;
|
|
@@ -111,6 +111,27 @@ interface ChainConfig<TContext = ProxyContext> {
|
|
|
111
111
|
}
|
|
112
112
|
type ProxyChainOptions<TContext = ProxyContext> = Partial<ChainConfig<TContext>>;
|
|
113
113
|
|
|
114
|
+
/**
|
|
115
|
+
* Creates a continuation action instructing the proxy chain to proceed to subsequent rules.
|
|
116
|
+
*
|
|
117
|
+
* @param options - Optional request and response header mutations.
|
|
118
|
+
* @returns NextResult token indicating pipeline continuation.
|
|
119
|
+
*/
|
|
120
|
+
declare function next(options?: NextOptions): NextResult;
|
|
121
|
+
/**
|
|
122
|
+
* Type guard verifying whether a returned value is a proxy continuation token.
|
|
123
|
+
*
|
|
124
|
+
* @param value - Value to test.
|
|
125
|
+
* @returns True if value is a NextResult continuation token.
|
|
126
|
+
*/
|
|
127
|
+
declare function isNextResult(value: unknown): value is NextResult;
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Creates an isolated per-request context instance.
|
|
131
|
+
* Backed by Map to eliminate prototype pollution risks.
|
|
132
|
+
*/
|
|
133
|
+
declare function createProxyContext(): ProxyContext;
|
|
134
|
+
|
|
114
135
|
/**
|
|
115
136
|
* Creates a reusable, scope-aware proxy rule function.
|
|
116
137
|
*
|
|
@@ -139,21 +160,6 @@ declare function proxyChain<TContext>(options: ProxyChainOptions<TContext> & {
|
|
|
139
160
|
createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
|
|
140
161
|
}, entries: Entry<TContext>[]): ProxyHandler;
|
|
141
162
|
|
|
142
|
-
/**
|
|
143
|
-
* Creates a continuation action instructing the proxy chain to proceed to subsequent rules.
|
|
144
|
-
*
|
|
145
|
-
* @param options - Optional request and response header mutations.
|
|
146
|
-
* @returns NextResult token indicating pipeline continuation.
|
|
147
|
-
*/
|
|
148
|
-
declare function next(options?: NextOptions): NextResult;
|
|
149
|
-
/**
|
|
150
|
-
* Type guard verifying whether a returned value is a proxy continuation token.
|
|
151
|
-
*
|
|
152
|
-
* @param value - Value to test.
|
|
153
|
-
* @returns True if value is a NextResult continuation token.
|
|
154
|
-
*/
|
|
155
|
-
declare function isNextResult(value: unknown): value is NextResult;
|
|
156
|
-
|
|
157
163
|
/**
|
|
158
164
|
* Builds a compiled Host matcher RegExp from domain names, `*.example.com` wildcards, or regex patterns.
|
|
159
165
|
*/
|
|
@@ -166,12 +172,6 @@ declare function host(matcher: HostMatcher): RegExp;
|
|
|
166
172
|
*/
|
|
167
173
|
declare function path(pattern: string | RegExp): RegExp;
|
|
168
174
|
|
|
169
|
-
/**
|
|
170
|
-
* Creates an isolated per-request context instance.
|
|
171
|
-
* Backed by Map to eliminate prototype pollution risks.
|
|
172
|
-
*/
|
|
173
|
-
declare function createProxyContext(): ProxyContext;
|
|
174
|
-
|
|
175
175
|
declare class RuleTimeoutError extends Error {
|
|
176
176
|
readonly ruleName: string;
|
|
177
177
|
readonly timeoutMs: number;
|
package/dist/index.d.ts
CHANGED
|
@@ -61,7 +61,7 @@ type ProxyFn<TContext = ProxyContext> = (req: NextRequest, ctx: TContext, event:
|
|
|
61
61
|
type ProxyRule<TContext = ProxyContext> = BaseProxyRule<ProxyFn<TContext>>;
|
|
62
62
|
type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>);
|
|
63
63
|
type Entry<TContext = ProxyContext> = ProxyFn<TContext> | ProxyRule<TContext>;
|
|
64
|
-
type MergeStrategy =
|
|
64
|
+
type MergeStrategy = 'last-write-wins' | 'first-write-wins' | ((key: string, existing: string, incoming: string) => string | null);
|
|
65
65
|
interface ChainLogger {
|
|
66
66
|
debug: (metaOrMsg: unknown, maybeMsg?: string) => void;
|
|
67
67
|
info: (metaOrMsg: unknown, maybeMsg?: string) => void;
|
|
@@ -111,6 +111,27 @@ interface ChainConfig<TContext = ProxyContext> {
|
|
|
111
111
|
}
|
|
112
112
|
type ProxyChainOptions<TContext = ProxyContext> = Partial<ChainConfig<TContext>>;
|
|
113
113
|
|
|
114
|
+
/**
|
|
115
|
+
* Creates a continuation action instructing the proxy chain to proceed to subsequent rules.
|
|
116
|
+
*
|
|
117
|
+
* @param options - Optional request and response header mutations.
|
|
118
|
+
* @returns NextResult token indicating pipeline continuation.
|
|
119
|
+
*/
|
|
120
|
+
declare function next(options?: NextOptions): NextResult;
|
|
121
|
+
/**
|
|
122
|
+
* Type guard verifying whether a returned value is a proxy continuation token.
|
|
123
|
+
*
|
|
124
|
+
* @param value - Value to test.
|
|
125
|
+
* @returns True if value is a NextResult continuation token.
|
|
126
|
+
*/
|
|
127
|
+
declare function isNextResult(value: unknown): value is NextResult;
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Creates an isolated per-request context instance.
|
|
131
|
+
* Backed by Map to eliminate prototype pollution risks.
|
|
132
|
+
*/
|
|
133
|
+
declare function createProxyContext(): ProxyContext;
|
|
134
|
+
|
|
114
135
|
/**
|
|
115
136
|
* Creates a reusable, scope-aware proxy rule function.
|
|
116
137
|
*
|
|
@@ -139,21 +160,6 @@ declare function proxyChain<TContext>(options: ProxyChainOptions<TContext> & {
|
|
|
139
160
|
createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
|
|
140
161
|
}, entries: Entry<TContext>[]): ProxyHandler;
|
|
141
162
|
|
|
142
|
-
/**
|
|
143
|
-
* Creates a continuation action instructing the proxy chain to proceed to subsequent rules.
|
|
144
|
-
*
|
|
145
|
-
* @param options - Optional request and response header mutations.
|
|
146
|
-
* @returns NextResult token indicating pipeline continuation.
|
|
147
|
-
*/
|
|
148
|
-
declare function next(options?: NextOptions): NextResult;
|
|
149
|
-
/**
|
|
150
|
-
* Type guard verifying whether a returned value is a proxy continuation token.
|
|
151
|
-
*
|
|
152
|
-
* @param value - Value to test.
|
|
153
|
-
* @returns True if value is a NextResult continuation token.
|
|
154
|
-
*/
|
|
155
|
-
declare function isNextResult(value: unknown): value is NextResult;
|
|
156
|
-
|
|
157
163
|
/**
|
|
158
164
|
* Builds a compiled Host matcher RegExp from domain names, `*.example.com` wildcards, or regex patterns.
|
|
159
165
|
*/
|
|
@@ -166,12 +172,6 @@ declare function host(matcher: HostMatcher): RegExp;
|
|
|
166
172
|
*/
|
|
167
173
|
declare function path(pattern: string | RegExp): RegExp;
|
|
168
174
|
|
|
169
|
-
/**
|
|
170
|
-
* Creates an isolated per-request context instance.
|
|
171
|
-
* Backed by Map to eliminate prototype pollution risks.
|
|
172
|
-
*/
|
|
173
|
-
declare function createProxyContext(): ProxyContext;
|
|
174
|
-
|
|
175
175
|
declare class RuleTimeoutError extends Error {
|
|
176
176
|
readonly ruleName: string;
|
|
177
177
|
readonly timeoutMs: number;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
// src/core/engine.ts
|
|
2
|
-
import { NextRequest, NextResponse as NextResponse2 } from "next/server";
|
|
3
|
-
|
|
4
1
|
// src/core/constants.ts
|
|
5
2
|
var NEXT = /* @__PURE__ */ Symbol.for("proxy-chain.next");
|
|
6
3
|
var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
|
|
@@ -37,6 +34,9 @@ function createProxyContext() {
|
|
|
37
34
|
return /* @__PURE__ */ new Map();
|
|
38
35
|
}
|
|
39
36
|
|
|
37
|
+
// src/core/engine.ts
|
|
38
|
+
import { NextRequest, NextResponse as NextResponse2 } from "next/server";
|
|
39
|
+
|
|
40
40
|
// src/core/headers.ts
|
|
41
41
|
function normalizeHeaderName(name) {
|
|
42
42
|
return name.toLowerCase();
|
|
@@ -179,6 +179,26 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
|
|
|
179
179
|
}
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
+
// src/core/host-folder-prefix.ts
|
|
183
|
+
function physicalFolderPrefix(raw) {
|
|
184
|
+
return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
|
|
185
|
+
}
|
|
186
|
+
function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
|
|
187
|
+
try {
|
|
188
|
+
const parsed = new URL(rewriteUrl, baseUrl);
|
|
189
|
+
if (!parsed.pathname.startsWith(folder)) {
|
|
190
|
+
parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
|
|
191
|
+
return parsed.toString();
|
|
192
|
+
}
|
|
193
|
+
return rewriteUrl;
|
|
194
|
+
} catch {
|
|
195
|
+
if (!rewriteUrl.startsWith(folder)) {
|
|
196
|
+
return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
|
|
197
|
+
}
|
|
198
|
+
return rewriteUrl;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
182
202
|
// src/core/logger.ts
|
|
183
203
|
var LEVEL_RANK = {
|
|
184
204
|
debug: 10,
|
|
@@ -250,7 +270,12 @@ function isScopeObject(value) {
|
|
|
250
270
|
return "host" in value || "path" in value;
|
|
251
271
|
}
|
|
252
272
|
function segmentToRegex(segment) {
|
|
253
|
-
if (segment
|
|
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]*)";
|
|
254
279
|
if (segment === "*") return "[^/]+";
|
|
255
280
|
if (segment.startsWith(":")) return "[^/]+";
|
|
256
281
|
return escapeRegex(segment);
|
|
@@ -270,7 +295,7 @@ function compileRegexPath(pattern) {
|
|
|
270
295
|
const wrapFull = !hasStart && !hasEnd;
|
|
271
296
|
const start = hasStart || wrapFull ? "^" : "";
|
|
272
297
|
const end = hasEnd || wrapFull ? "$" : "";
|
|
273
|
-
return toStatelessRegExp(new RegExp(`${start}
|
|
298
|
+
return toStatelessRegExp(new RegExp(`${start}(?:${source})${end}`, pattern.flags));
|
|
274
299
|
}
|
|
275
300
|
function compileStringPath(pattern) {
|
|
276
301
|
const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
|
|
@@ -286,7 +311,7 @@ function compileStringPath(pattern) {
|
|
|
286
311
|
pathPattern = prefix ? `/${prefix}/[^/]+` : `/[^/]+`;
|
|
287
312
|
} else if (trailingGlobstar) {
|
|
288
313
|
const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
|
|
289
|
-
pathPattern = prefix ? `/${prefix}(
|
|
314
|
+
pathPattern = prefix ? `/${prefix}(?:/[\\s\\S]*)?` : `/(?:[\\s\\S]*)?`;
|
|
290
315
|
} else {
|
|
291
316
|
pathPattern = `/${segments.map(segmentToRegex).join("/")}`;
|
|
292
317
|
}
|
|
@@ -343,10 +368,17 @@ function toRule(entry) {
|
|
|
343
368
|
const rule = entry;
|
|
344
369
|
const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
|
|
345
370
|
const name = extractMeaningfulName(rule.name) ?? runName;
|
|
346
|
-
const harden = (scopes) => scopes?.map((s) =>
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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
|
+
});
|
|
350
382
|
return {
|
|
351
383
|
...rule,
|
|
352
384
|
name: name ?? void 0,
|
|
@@ -381,9 +413,18 @@ function normalizeHost(raw) {
|
|
|
381
413
|
const end = first.indexOf("]");
|
|
382
414
|
return end === -1 ? first : first.slice(1, end);
|
|
383
415
|
}
|
|
384
|
-
const withoutPort = first.replace(/:\d+$/, "");
|
|
416
|
+
const withoutPort = first.replace(/:\d+$/, "").replace(/\.$/, "");
|
|
385
417
|
return withoutPort || null;
|
|
386
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
|
+
}
|
|
387
428
|
function scopeKey(scope) {
|
|
388
429
|
return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
|
|
389
430
|
}
|
|
@@ -450,6 +491,11 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
450
491
|
if (res == null) {
|
|
451
492
|
return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
|
|
452
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
|
+
}
|
|
453
499
|
if (isNextResult(res)) {
|
|
454
500
|
let request;
|
|
455
501
|
if (res.request) {
|
|
@@ -472,7 +518,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
472
518
|
cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
|
|
473
519
|
};
|
|
474
520
|
}
|
|
475
|
-
if (res.headers.get("x-middleware-next") === "1") {
|
|
521
|
+
if (res instanceof NextResponse && res.headers.get("x-middleware-next") === "1") {
|
|
476
522
|
let request;
|
|
477
523
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
478
524
|
if ([...decoded.keys()].length > 0) {
|
|
@@ -487,7 +533,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
487
533
|
cookies: cookieItemsFromHeaders(res.headers)
|
|
488
534
|
};
|
|
489
535
|
}
|
|
490
|
-
const rewriteHeader = res.headers.get("x-middleware-rewrite");
|
|
536
|
+
const rewriteHeader = res instanceof NextResponse ? res.headers.get("x-middleware-rewrite") : null;
|
|
491
537
|
if (rewriteHeader && (res.status === 200 || !res.status)) {
|
|
492
538
|
let request;
|
|
493
539
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
@@ -537,9 +583,9 @@ var RuleTimeoutError = class extends Error {
|
|
|
537
583
|
}
|
|
538
584
|
};
|
|
539
585
|
function assertFiniteRuleTimeoutMs(ruleTimeoutMs) {
|
|
540
|
-
if (ruleTimeoutMs != null && !Number.isFinite(ruleTimeoutMs)) {
|
|
586
|
+
if (ruleTimeoutMs != null && (!Number.isFinite(ruleTimeoutMs) || ruleTimeoutMs < 0)) {
|
|
541
587
|
throw new RangeError(
|
|
542
|
-
`[proxy-chain] ruleTimeoutMs must be a finite
|
|
588
|
+
`[proxy-chain] ruleTimeoutMs must be a finite number >= 0 (0 disables), got ${ruleTimeoutMs}`
|
|
543
589
|
);
|
|
544
590
|
}
|
|
545
591
|
}
|
|
@@ -560,6 +606,18 @@ async function withRuleTimeout(promise, timeoutMs, ruleName) {
|
|
|
560
606
|
}
|
|
561
607
|
|
|
562
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
|
+
}
|
|
563
621
|
function isPathFilter(value) {
|
|
564
622
|
if (value === null || typeof value !== "object") return false;
|
|
565
623
|
if ("nextUrl" in value) return false;
|
|
@@ -601,24 +659,6 @@ function resolveConfig(overrides, fallbackCreateContext) {
|
|
|
601
659
|
assertFiniteRuleTimeoutMs(config.ruleTimeoutMs);
|
|
602
660
|
return config;
|
|
603
661
|
}
|
|
604
|
-
function physicalFolderPrefix(raw) {
|
|
605
|
-
return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
|
|
606
|
-
}
|
|
607
|
-
function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
|
|
608
|
-
try {
|
|
609
|
-
const parsed = new URL(rewriteUrl, baseUrl);
|
|
610
|
-
if (!parsed.pathname.startsWith(folder)) {
|
|
611
|
-
parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
|
|
612
|
-
return parsed.toString();
|
|
613
|
-
}
|
|
614
|
-
return rewriteUrl;
|
|
615
|
-
} catch {
|
|
616
|
-
if (!rewriteUrl.startsWith(folder)) {
|
|
617
|
-
return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
|
|
618
|
-
}
|
|
619
|
-
return rewriteUrl;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
662
|
function proxyChain(optionsOrEntries, maybeEntries) {
|
|
623
663
|
const options = Array.isArray(optionsOrEntries) ? {} : optionsOrEntries;
|
|
624
664
|
const entries = (Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries) ?? [];
|
|
@@ -678,6 +718,58 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
678
718
|
appliedRequestOverrides.set(k, v);
|
|
679
719
|
});
|
|
680
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
|
+
};
|
|
681
773
|
try {
|
|
682
774
|
for (let i = 0; i < rules.length; i++) {
|
|
683
775
|
const rule = rules[i];
|
|
@@ -686,7 +778,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
686
778
|
const reqHost = normalizeHost(
|
|
687
779
|
activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
|
|
688
780
|
);
|
|
689
|
-
|
|
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;
|
|
690
789
|
const startedAt = debug ? performance.now() : 0;
|
|
691
790
|
let raw;
|
|
692
791
|
try {
|
|
@@ -696,60 +795,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
696
795
|
label
|
|
697
796
|
);
|
|
698
797
|
} catch (err) {
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
});
|
|
711
|
-
cookieWrites.push({
|
|
712
|
-
ruleIndex: i,
|
|
713
|
-
ruleName: label,
|
|
714
|
-
items: cookieItemsFromHeaders(recovered.headers)
|
|
715
|
-
});
|
|
716
|
-
if (debug) {
|
|
717
|
-
logger.debug(
|
|
718
|
-
formatPipelineLine({
|
|
719
|
-
method,
|
|
720
|
-
path: pathname,
|
|
721
|
-
name: label,
|
|
722
|
-
traceId,
|
|
723
|
-
outcome: {
|
|
724
|
-
kind: "stop",
|
|
725
|
-
duration: performance.now() - startedAt,
|
|
726
|
-
status: recovered.status
|
|
727
|
-
}
|
|
728
|
-
})
|
|
729
|
-
);
|
|
730
|
-
}
|
|
731
|
-
return finalizeResponse(
|
|
732
|
-
recovered,
|
|
733
|
-
headerWrites,
|
|
734
|
-
cookieWrites,
|
|
735
|
-
headerMergeStrategy,
|
|
736
|
-
cookieMergeStrategy,
|
|
737
|
-
logger,
|
|
738
|
-
debug
|
|
739
|
-
);
|
|
740
|
-
} else {
|
|
741
|
-
return safeInternalError();
|
|
742
|
-
}
|
|
743
|
-
} catch (onErrorErr) {
|
|
744
|
-
logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
|
|
745
|
-
return safeInternalError();
|
|
746
|
-
}
|
|
747
|
-
} else {
|
|
748
|
-
logger.error({ rule: label, err }, "rule threw");
|
|
749
|
-
return safeInternalError();
|
|
750
|
-
}
|
|
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);
|
|
751
809
|
}
|
|
752
|
-
const outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
|
|
753
810
|
const duration = debug ? performance.now() - startedAt : 0;
|
|
754
811
|
if (outcome.kind === "continue") {
|
|
755
812
|
if (outcome.rewriteUrl) {
|
|
@@ -784,6 +841,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
784
841
|
}
|
|
785
842
|
continue;
|
|
786
843
|
}
|
|
844
|
+
stripRoutingOverrides(outcome.response);
|
|
787
845
|
headerWrites.push({
|
|
788
846
|
ruleIndex: i,
|
|
789
847
|
ruleName: label,
|
|
@@ -865,7 +923,18 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
865
923
|
if (config.onError) {
|
|
866
924
|
try {
|
|
867
925
|
const recovered = await config.onError(err, -1, materializeRequest(), ctx);
|
|
868
|
-
if (recovered instanceof Response
|
|
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
|
+
}
|
|
869
938
|
} catch {
|
|
870
939
|
}
|
|
871
940
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@klnap/next-proxy-chain",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "
|
|
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"
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
"typecheck": "tsc -p tsconfig.json",
|
|
53
53
|
"test": "bun test",
|
|
54
54
|
"test:watch": "bun test --watch",
|
|
55
|
+
"lint": "biome check .",
|
|
55
56
|
"clean": "rm -rf dist coverage",
|
|
56
57
|
"prepublishOnly": "bun run clean && bun run typecheck && bun test && bun run build"
|
|
57
58
|
},
|
|
@@ -60,6 +61,7 @@
|
|
|
60
61
|
},
|
|
61
62
|
"devDependencies": {
|
|
62
63
|
"@types/bun": "^1.4.0",
|
|
64
|
+
"@biomejs/biome": "2.5.14",
|
|
63
65
|
"@types/node": "^20",
|
|
64
66
|
"next": "16.3.2",
|
|
65
67
|
"tsup": "^8.4.0",
|