@klnap/next-proxy-chain 1.0.3 → 1.0.5
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 +62 -0
- package/LICENSE +1 -1
- package/README.md +72 -54
- package/dist/index.cjs +333 -316
- package/dist/index.d.cts +57 -161
- package/dist/index.d.ts +57 -161
- package/dist/index.js +332 -285
- package/package.json +16 -11
package/dist/index.js
CHANGED
|
@@ -21,177 +21,21 @@ var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
|
|
|
21
21
|
"x-middleware-override-headers"
|
|
22
22
|
]);
|
|
23
23
|
|
|
24
|
+
// src/core/actions.ts
|
|
25
|
+
function next(options = {}) {
|
|
26
|
+
return { [NEXT]: true, ...options };
|
|
27
|
+
}
|
|
28
|
+
function isNextResult(value) {
|
|
29
|
+
return typeof value === "object" && value !== null && NEXT in value;
|
|
30
|
+
}
|
|
31
|
+
|
|
24
32
|
// src/core/context.ts
|
|
25
33
|
function createProxyContext() {
|
|
26
34
|
return /* @__PURE__ */ new Map();
|
|
27
35
|
}
|
|
28
36
|
|
|
29
|
-
// src/core/
|
|
30
|
-
|
|
31
|
-
function extractMeaningfulName(value) {
|
|
32
|
-
if (!value || RESERVED_FN_NAMES.has(value)) return void 0;
|
|
33
|
-
return value;
|
|
34
|
-
}
|
|
35
|
-
function toStatelessRegExp(re) {
|
|
36
|
-
const flags = re.flags.replace(/[gy]/g, "");
|
|
37
|
-
return flags === re.flags ? re : new RegExp(re.source, flags);
|
|
38
|
-
}
|
|
39
|
-
function escapeRegex(value) {
|
|
40
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
41
|
-
}
|
|
42
|
-
function host(matcher) {
|
|
43
|
-
const list = Array.isArray(matcher) ? matcher : [matcher];
|
|
44
|
-
const parts = list.map((m) => {
|
|
45
|
-
if (m instanceof RegExp) return `(?:${toStatelessRegExp(m).source})`;
|
|
46
|
-
return `(?:${escapeRegex(m.toLowerCase())})`;
|
|
47
|
-
});
|
|
48
|
-
return toStatelessRegExp(new RegExp(`^(?:${parts.join("|")})$`, "i"));
|
|
49
|
-
}
|
|
50
|
-
function isScopeObject(value) {
|
|
51
|
-
return "host" in value || "path" in value;
|
|
52
|
-
}
|
|
53
|
-
function segmentToRegex(segment) {
|
|
54
|
-
if (segment === "**") return "(?:.*)";
|
|
55
|
-
if (segment === "*") return "[^/]+";
|
|
56
|
-
if (segment.startsWith(":")) return "[^/]+";
|
|
57
|
-
return escapeRegex(segment);
|
|
58
|
-
}
|
|
59
|
-
function path(pattern, options = {}) {
|
|
60
|
-
const { locales = [] } = options;
|
|
61
|
-
const localePrefix = locales.length > 0 ? `(?:(?:${locales.map(escapeRegex).join("|")})\\/)?` : "";
|
|
62
|
-
if (pattern instanceof RegExp) {
|
|
63
|
-
const body2 = pattern.source.replace(/^\^/, "").replace(/\$$/, "");
|
|
64
|
-
const needsStart = !pattern.source.startsWith("^");
|
|
65
|
-
const needsEnd = !pattern.source.endsWith("$");
|
|
66
|
-
return toStatelessRegExp(
|
|
67
|
-
new RegExp(
|
|
68
|
-
`${needsStart ? "^" : ""}${localePrefix ? `/${localePrefix}` : ""}${body2}${needsEnd ? "$" : ""}`,
|
|
69
|
-
pattern.flags
|
|
70
|
-
)
|
|
71
|
-
);
|
|
72
|
-
}
|
|
73
|
-
const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
|
|
74
|
-
const segments = normalized.slice(1).split("/");
|
|
75
|
-
const trailingStar = segments.length > 0 && segments[segments.length - 1] === "*";
|
|
76
|
-
const suffix = trailingStar ? "(?:\\/.*)?$" : "$";
|
|
77
|
-
const body = trailingStar ? segments.slice(0, -1).map(segmentToRegex).concat("[^/]+").join("\\/") : segments.map(segmentToRegex).join("\\/");
|
|
78
|
-
return new RegExp(`^/${localePrefix}${body}${suffix}`);
|
|
79
|
-
}
|
|
80
|
-
function toPathRegex(matcher, options) {
|
|
81
|
-
const list = Array.isArray(matcher) ? matcher : [matcher];
|
|
82
|
-
const regexes = list.map((m) => path(m, options));
|
|
83
|
-
if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
|
|
84
|
-
return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
|
|
85
|
-
}
|
|
86
|
-
function compileScopes(input, pathOptions) {
|
|
87
|
-
if (input == null) return void 0;
|
|
88
|
-
const list = Array.isArray(input) ? input : [input];
|
|
89
|
-
const compilePath = (matcher) => {
|
|
90
|
-
if (Array.isArray(matcher)) {
|
|
91
|
-
const parts = matcher.map(
|
|
92
|
-
(m) => typeof m === "string" ? path(m, pathOptions) : toStatelessRegExp(m)
|
|
93
|
-
);
|
|
94
|
-
if (parts.length === 1) return parts[0];
|
|
95
|
-
return toStatelessRegExp(new RegExp(`(?:${parts.map((r) => `(?:${r.source})`).join("|")})`));
|
|
96
|
-
}
|
|
97
|
-
return typeof matcher === "string" ? path(matcher, pathOptions) : toStatelessRegExp(matcher);
|
|
98
|
-
};
|
|
99
|
-
const compiled = [];
|
|
100
|
-
for (const item of list) {
|
|
101
|
-
if (typeof item === "string" || item instanceof RegExp) {
|
|
102
|
-
compiled.push({ path: compilePath(item) });
|
|
103
|
-
continue;
|
|
104
|
-
}
|
|
105
|
-
if (item && typeof item === "object" && isScopeObject(item)) {
|
|
106
|
-
if (item.host == null && item.path == null) {
|
|
107
|
-
throw new Error("[proxy-chain] scope needs at least `host` or `path`");
|
|
108
|
-
}
|
|
109
|
-
compiled.push({
|
|
110
|
-
host: item.host != null ? host(item.host) : void 0,
|
|
111
|
-
path: item.path != null ? compilePath(item.path) : void 0
|
|
112
|
-
});
|
|
113
|
-
continue;
|
|
114
|
-
}
|
|
115
|
-
throw new Error("[proxy-chain] invalid include/exclude scope");
|
|
116
|
-
}
|
|
117
|
-
return compiled;
|
|
118
|
-
}
|
|
119
|
-
function scopeMatches(pathname, hostname, scope) {
|
|
120
|
-
if (scope.host) {
|
|
121
|
-
if (!hostname || !scope.host.test(hostname)) return false;
|
|
122
|
-
}
|
|
123
|
-
if (scope.path) {
|
|
124
|
-
if (!scope.path.test(pathname)) return false;
|
|
125
|
-
}
|
|
126
|
-
return true;
|
|
127
|
-
}
|
|
128
|
-
function toRule(entry) {
|
|
129
|
-
if (typeof entry === "function") {
|
|
130
|
-
const name2 = extractMeaningfulName(entry.name);
|
|
131
|
-
return name2 ? { run: entry, name: name2 } : { run: entry };
|
|
132
|
-
}
|
|
133
|
-
const rule = entry;
|
|
134
|
-
const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
|
|
135
|
-
const name = extractMeaningfulName(rule.name) ?? runName;
|
|
136
|
-
const harden = (scopes) => scopes?.map((s) => ({
|
|
137
|
-
host: s.host ? toStatelessRegExp(s.host) : void 0,
|
|
138
|
-
path: s.path ? toStatelessRegExp(s.path) : void 0
|
|
139
|
-
}));
|
|
140
|
-
return {
|
|
141
|
-
...rule,
|
|
142
|
-
name: name ?? void 0,
|
|
143
|
-
include: harden(rule.include),
|
|
144
|
-
exclude: harden(rule.exclude)
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
function ruleLabel(rule, index) {
|
|
148
|
-
const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
|
|
149
|
-
return extractMeaningfulName(rule.name) ?? runName ?? `rule#${index}`;
|
|
150
|
-
}
|
|
151
|
-
function withPaths(entry, filter) {
|
|
152
|
-
const base = toRule(entry);
|
|
153
|
-
const opts = filter.pathOptions;
|
|
154
|
-
const include = compileScopes(filter.include, opts);
|
|
155
|
-
const exclude = compileScopes(filter.exclude, opts);
|
|
156
|
-
const name = filter.name ?? base.name;
|
|
157
|
-
assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
|
|
158
|
-
return { run: base.run, include, exclude, name };
|
|
159
|
-
}
|
|
160
|
-
function ruleMatches(pathname, hostname, rule) {
|
|
161
|
-
if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) return false;
|
|
162
|
-
if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
|
|
163
|
-
return false;
|
|
164
|
-
}
|
|
165
|
-
return true;
|
|
166
|
-
}
|
|
167
|
-
function pathMatches(pathname, rule) {
|
|
168
|
-
return ruleMatches(pathname, null, rule);
|
|
169
|
-
}
|
|
170
|
-
function normalizeHost(raw) {
|
|
171
|
-
if (!raw) return null;
|
|
172
|
-
const first = raw.split(",")[0]?.trim().toLowerCase();
|
|
173
|
-
if (!first) return null;
|
|
174
|
-
if (first.startsWith("[")) {
|
|
175
|
-
const end = first.indexOf("]");
|
|
176
|
-
return end === -1 ? first : first.slice(1, end);
|
|
177
|
-
}
|
|
178
|
-
const withoutPort = first.replace(/:\d+$/, "");
|
|
179
|
-
return withoutPort || null;
|
|
180
|
-
}
|
|
181
|
-
function scopeKey(scope) {
|
|
182
|
-
return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
|
|
183
|
-
}
|
|
184
|
-
function assertIncludeExcludeNoOverlap(include, exclude, label) {
|
|
185
|
-
if (!include?.length || !exclude?.length) return;
|
|
186
|
-
const excluded = new Set(exclude.map(scopeKey));
|
|
187
|
-
for (const scope of include) {
|
|
188
|
-
if (excluded.has(scopeKey(scope))) {
|
|
189
|
-
throw new Error(
|
|
190
|
-
`[proxy-chain] ${label}: include and exclude share an identical scope. Remove one.`
|
|
191
|
-
);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
}
|
|
37
|
+
// src/core/engine.ts
|
|
38
|
+
import { NextRequest, NextResponse as NextResponse2 } from "next/server";
|
|
195
39
|
|
|
196
40
|
// src/core/headers.ts
|
|
197
41
|
function normalizeHeaderName(name) {
|
|
@@ -235,15 +79,32 @@ function parseCookieName(setCookie) {
|
|
|
235
79
|
return (eq === -1 ? setCookie : setCookie.slice(0, eq)).trim();
|
|
236
80
|
}
|
|
237
81
|
function listSetCookie(headers) {
|
|
238
|
-
|
|
239
|
-
if (typeof extended.getSetCookie === "function") return extended.getSetCookie();
|
|
82
|
+
if (typeof headers.getSetCookie === "function") return headers.getSetCookie();
|
|
240
83
|
const single = headers.get("set-cookie");
|
|
241
84
|
return single ? [single] : [];
|
|
242
85
|
}
|
|
86
|
+
function cookieAttribute(setCookie, name) {
|
|
87
|
+
const parts = setCookie.split(";");
|
|
88
|
+
for (let i = 1; i < parts.length; i++) {
|
|
89
|
+
const piece = parts[i];
|
|
90
|
+
if (!piece) continue;
|
|
91
|
+
const eq = piece.indexOf("=");
|
|
92
|
+
const key = (eq === -1 ? piece : piece.slice(0, eq)).trim().toLowerCase();
|
|
93
|
+
if (key !== name) continue;
|
|
94
|
+
return (eq === -1 ? "" : piece.slice(eq + 1)).trim();
|
|
95
|
+
}
|
|
96
|
+
return "";
|
|
97
|
+
}
|
|
98
|
+
function cookieIdentityKey(setCookie) {
|
|
99
|
+
const name = parseCookieName(setCookie);
|
|
100
|
+
const path2 = cookieAttribute(setCookie, "path");
|
|
101
|
+
const domain = cookieAttribute(setCookie, "domain").toLowerCase();
|
|
102
|
+
return `${name};domain=${domain};path=${path2}`;
|
|
103
|
+
}
|
|
243
104
|
function cookieItemsFromHeaders(headers) {
|
|
244
105
|
const map = /* @__PURE__ */ new Map();
|
|
245
106
|
for (const value of listSetCookie(headers)) {
|
|
246
|
-
map.set(
|
|
107
|
+
map.set(cookieIdentityKey(value), value);
|
|
247
108
|
}
|
|
248
109
|
return map;
|
|
249
110
|
}
|
|
@@ -303,7 +164,12 @@ function mergeWrites(writes, strategy, onConflict) {
|
|
|
303
164
|
}
|
|
304
165
|
return resolved;
|
|
305
166
|
}
|
|
306
|
-
function applyMergedToResponse(res, headers, cookies) {
|
|
167
|
+
function applyMergedToResponse(res, headers, cookies, dropHeaders) {
|
|
168
|
+
if (dropHeaders) {
|
|
169
|
+
for (const key of dropHeaders) {
|
|
170
|
+
if (!headers.has(key)) res.headers.delete(key);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
307
173
|
for (const [key, value] of headers) {
|
|
308
174
|
res.headers.set(key, value);
|
|
309
175
|
}
|
|
@@ -313,12 +179,24 @@ function applyMergedToResponse(res, headers, cookies) {
|
|
|
313
179
|
}
|
|
314
180
|
}
|
|
315
181
|
|
|
316
|
-
// src/core/
|
|
317
|
-
function
|
|
318
|
-
return
|
|
182
|
+
// src/core/host-folder-prefix.ts
|
|
183
|
+
function physicalFolderPrefix(raw) {
|
|
184
|
+
return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
|
|
319
185
|
}
|
|
320
|
-
function
|
|
321
|
-
|
|
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
|
+
}
|
|
322
200
|
}
|
|
323
201
|
|
|
324
202
|
// src/core/logger.ts
|
|
@@ -364,27 +242,180 @@ function formatPipelineLine(input) {
|
|
|
364
242
|
}
|
|
365
243
|
}
|
|
366
244
|
|
|
367
|
-
// src/core/
|
|
368
|
-
var
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
245
|
+
// src/core/matching.ts
|
|
246
|
+
var RESERVED_FN_NAMES = /* @__PURE__ */ new Set(["", "proxy", "anonymous", "run", "next"]);
|
|
247
|
+
function extractMeaningfulName(value) {
|
|
248
|
+
if (!value || RESERVED_FN_NAMES.has(value)) return void 0;
|
|
249
|
+
return value;
|
|
250
|
+
}
|
|
251
|
+
function toStatelessRegExp(re) {
|
|
252
|
+
const flags = re.flags.replace(/[gy]/g, "");
|
|
253
|
+
return flags === re.flags ? re : new RegExp(re.source, flags);
|
|
254
|
+
}
|
|
255
|
+
function escapeRegex(value) {
|
|
256
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
257
|
+
}
|
|
258
|
+
function hostGlobToRegex(value) {
|
|
259
|
+
return escapeRegex(value.toLowerCase()).replace(/\\\*/g, "[^.]+");
|
|
260
|
+
}
|
|
261
|
+
function host(matcher) {
|
|
262
|
+
const list = Array.isArray(matcher) ? matcher : [matcher];
|
|
263
|
+
const parts = list.map((m) => {
|
|
264
|
+
if (m instanceof RegExp) return `(?:${toStatelessRegExp(m).source})`;
|
|
265
|
+
return `(?:${hostGlobToRegex(m)})`;
|
|
383
266
|
});
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
267
|
+
return toStatelessRegExp(new RegExp(`^(?:${parts.join("|")})$`, "i"));
|
|
268
|
+
}
|
|
269
|
+
function isScopeObject(value) {
|
|
270
|
+
return "host" in value || "path" in value;
|
|
271
|
+
}
|
|
272
|
+
function segmentToRegex(segment) {
|
|
273
|
+
if (segment === "**") return "(?:.*)";
|
|
274
|
+
if (segment === "*") return "[^/]+";
|
|
275
|
+
if (segment.startsWith(":")) return "[^/]+";
|
|
276
|
+
return escapeRegex(segment);
|
|
277
|
+
}
|
|
278
|
+
function hasEndAnchor(source) {
|
|
279
|
+
if (!source.endsWith("$")) return false;
|
|
280
|
+
let slashes = 0;
|
|
281
|
+
for (let i = source.length - 2; i >= 0 && source[i] === "\\"; i--) slashes++;
|
|
282
|
+
return slashes % 2 === 0;
|
|
283
|
+
}
|
|
284
|
+
function compileRegexPath(pattern) {
|
|
285
|
+
let source = pattern.source;
|
|
286
|
+
const hasStart = source.startsWith("^");
|
|
287
|
+
const hasEnd = hasEndAnchor(source);
|
|
288
|
+
if (hasStart) source = source.slice(1);
|
|
289
|
+
if (hasEnd) source = source.slice(0, -1);
|
|
290
|
+
const wrapFull = !hasStart && !hasEnd;
|
|
291
|
+
const start = hasStart || wrapFull ? "^" : "";
|
|
292
|
+
const end = hasEnd || wrapFull ? "$" : "";
|
|
293
|
+
return toStatelessRegExp(new RegExp(`${start}${source}${end}`, pattern.flags));
|
|
294
|
+
}
|
|
295
|
+
function compileStringPath(pattern) {
|
|
296
|
+
const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
|
|
297
|
+
const segments = normalized === "/" ? [] : normalized.slice(1).split("/");
|
|
298
|
+
const last = segments[segments.length - 1];
|
|
299
|
+
const trailingStar = last === "*";
|
|
300
|
+
const trailingGlobstar = last === "**";
|
|
301
|
+
let pathPattern;
|
|
302
|
+
if (normalized === "/") {
|
|
303
|
+
pathPattern = "/";
|
|
304
|
+
} else if (trailingStar) {
|
|
305
|
+
const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
|
|
306
|
+
pathPattern = prefix ? `/${prefix}/[^/]+` : `/[^/]+`;
|
|
307
|
+
} else if (trailingGlobstar) {
|
|
308
|
+
const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
|
|
309
|
+
pathPattern = prefix ? `/${prefix}(?:/.*)?` : `/(?:.*)?`;
|
|
310
|
+
} else {
|
|
311
|
+
pathPattern = `/${segments.map(segmentToRegex).join("/")}`;
|
|
312
|
+
}
|
|
313
|
+
return new RegExp(`^${pathPattern}$`);
|
|
314
|
+
}
|
|
315
|
+
function path(pattern) {
|
|
316
|
+
if (pattern instanceof RegExp) return compileRegexPath(pattern);
|
|
317
|
+
return compileStringPath(pattern);
|
|
318
|
+
}
|
|
319
|
+
function toPathRegex(matcher) {
|
|
320
|
+
const list = Array.isArray(matcher) ? matcher : [matcher];
|
|
321
|
+
const regexes = list.map((m) => path(m));
|
|
322
|
+
if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
|
|
323
|
+
return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
|
|
324
|
+
}
|
|
325
|
+
function compileScopes(input) {
|
|
326
|
+
if (input == null) return void 0;
|
|
327
|
+
const list = Array.isArray(input) ? input : [input];
|
|
328
|
+
const compilePath = (matcher) => toPathRegex(matcher);
|
|
329
|
+
const compiled = [];
|
|
330
|
+
for (const item of list) {
|
|
331
|
+
if (typeof item === "string" || item instanceof RegExp) {
|
|
332
|
+
compiled.push({ path: compilePath(item) });
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (item && typeof item === "object" && isScopeObject(item)) {
|
|
336
|
+
if (item.host == null && item.path == null) {
|
|
337
|
+
throw new Error("[proxy-chain] scope needs at least `host` or `path`");
|
|
338
|
+
}
|
|
339
|
+
compiled.push({
|
|
340
|
+
host: item.host != null ? host(item.host) : void 0,
|
|
341
|
+
path: item.path != null ? compilePath(item.path) : void 0
|
|
342
|
+
});
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
throw new Error("[proxy-chain] invalid include/exclude scope");
|
|
346
|
+
}
|
|
347
|
+
return compiled;
|
|
348
|
+
}
|
|
349
|
+
function scopeMatches(pathname, hostname, scope) {
|
|
350
|
+
if (scope.host) {
|
|
351
|
+
if (!hostname || !scope.host.test(hostname)) return false;
|
|
352
|
+
}
|
|
353
|
+
if (scope.path) {
|
|
354
|
+
if (!scope.path.test(pathname)) return false;
|
|
355
|
+
}
|
|
356
|
+
return true;
|
|
357
|
+
}
|
|
358
|
+
function toRule(entry) {
|
|
359
|
+
if (typeof entry === "function") {
|
|
360
|
+
const name2 = extractMeaningfulName(entry.name);
|
|
361
|
+
return name2 ? { run: entry, name: name2 } : { run: entry };
|
|
362
|
+
}
|
|
363
|
+
const rule = entry;
|
|
364
|
+
const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
|
|
365
|
+
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
|
+
}));
|
|
370
|
+
return {
|
|
371
|
+
...rule,
|
|
372
|
+
name: name ?? void 0,
|
|
373
|
+
include: harden(rule.include),
|
|
374
|
+
exclude: harden(rule.exclude)
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
function ruleLabel(rule, index) {
|
|
378
|
+
const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
|
|
379
|
+
return extractMeaningfulName(rule.name) ?? runName ?? `rule#${index}`;
|
|
380
|
+
}
|
|
381
|
+
function withPaths(entry, filter) {
|
|
382
|
+
const base = toRule(entry);
|
|
383
|
+
const include = compileScopes(filter.include);
|
|
384
|
+
const exclude = compileScopes(filter.exclude);
|
|
385
|
+
const name = filter.name ?? base.name;
|
|
386
|
+
assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
|
|
387
|
+
return { run: base.run, include, exclude, name };
|
|
388
|
+
}
|
|
389
|
+
function ruleMatches(pathname, hostname, rule) {
|
|
390
|
+
if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) return false;
|
|
391
|
+
if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
return true;
|
|
395
|
+
}
|
|
396
|
+
function normalizeHost(raw) {
|
|
397
|
+
if (!raw) return null;
|
|
398
|
+
const first = raw.split(",")[0]?.trim().toLowerCase();
|
|
399
|
+
if (!first) return null;
|
|
400
|
+
if (first.startsWith("[")) {
|
|
401
|
+
const end = first.indexOf("]");
|
|
402
|
+
return end === -1 ? first : first.slice(1, end);
|
|
403
|
+
}
|
|
404
|
+
const withoutPort = first.replace(/:\d+$/, "");
|
|
405
|
+
return withoutPort || null;
|
|
406
|
+
}
|
|
407
|
+
function scopeKey(scope) {
|
|
408
|
+
return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
|
|
409
|
+
}
|
|
410
|
+
function assertIncludeExcludeNoOverlap(include, exclude, label) {
|
|
411
|
+
if (!include?.length || !exclude?.length) return;
|
|
412
|
+
const excluded = new Set(exclude.map(scopeKey));
|
|
413
|
+
for (const scope of include) {
|
|
414
|
+
if (excluded.has(scopeKey(scope))) {
|
|
415
|
+
throw new Error(
|
|
416
|
+
`[proxy-chain] ${label}: include and exclude share an identical scope. Remove one.`
|
|
417
|
+
);
|
|
418
|
+
}
|
|
388
419
|
}
|
|
389
420
|
}
|
|
390
421
|
|
|
@@ -396,26 +427,42 @@ function safeInternalError() {
|
|
|
396
427
|
headers: { "content-type": "text/plain; charset=utf-8" }
|
|
397
428
|
});
|
|
398
429
|
}
|
|
399
|
-
var
|
|
430
|
+
var UNSUPPORTED_OVERRIDE_MSG = "[proxy-chain] Warning: platform NextResponse.next() does not support x-middleware-next header overrides.";
|
|
431
|
+
var VERIFY_OVERRIDE_MSG = "[proxy-chain] Warning: unable to verify NextResponse request override mechanism.";
|
|
432
|
+
var cachedOverrideProbe = null;
|
|
433
|
+
var overrideProbeForTests = null;
|
|
434
|
+
function runOverrideProbe() {
|
|
435
|
+
if (overrideProbeForTests) return overrideProbeForTests();
|
|
436
|
+
const testRes = NextResponse.next({
|
|
437
|
+
request: { headers: new Headers({ "x-proxy-chain-probe": "1" }) }
|
|
438
|
+
});
|
|
439
|
+
return testRes.headers.get("x-middleware-next") === "1";
|
|
440
|
+
}
|
|
441
|
+
function throwForCachedProbe(probe) {
|
|
442
|
+
if (probe.kind === "unsupported") throw new Error(UNSUPPORTED_OVERRIDE_MSG);
|
|
443
|
+
throw probe.err instanceof Error ? probe.err : new Error(VERIFY_OVERRIDE_MSG);
|
|
444
|
+
}
|
|
445
|
+
function resolveCachedProbe(probe, strict) {
|
|
446
|
+
if (probe.kind === "supported") return true;
|
|
447
|
+
if (strict) throwForCachedProbe(probe);
|
|
448
|
+
return false;
|
|
449
|
+
}
|
|
400
450
|
function assertOverrideMechanismSupported(strict = false) {
|
|
401
|
-
if (
|
|
451
|
+
if (cachedOverrideProbe !== null) return resolveCachedProbe(cachedOverrideProbe, strict);
|
|
402
452
|
try {
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
cachedOverrideSupported = isSupported;
|
|
408
|
-
if (!isSupported) {
|
|
409
|
-
const msg = "[proxy-chain] Warning: platform NextResponse.next() does not support x-middleware-next header overrides.";
|
|
410
|
-
if (strict) throw new Error(msg);
|
|
411
|
-
console.warn(msg);
|
|
453
|
+
const isSupported = runOverrideProbe();
|
|
454
|
+
if (isSupported) {
|
|
455
|
+
cachedOverrideProbe = { kind: "supported" };
|
|
456
|
+
return true;
|
|
412
457
|
}
|
|
413
|
-
|
|
458
|
+
cachedOverrideProbe = { kind: "unsupported" };
|
|
459
|
+
if (strict) throw new Error(UNSUPPORTED_OVERRIDE_MSG);
|
|
460
|
+
console.warn(UNSUPPORTED_OVERRIDE_MSG);
|
|
461
|
+
return false;
|
|
414
462
|
} catch (err) {
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
console.warn(msg, err);
|
|
463
|
+
cachedOverrideProbe = { kind: "error", err };
|
|
464
|
+
if (strict) throw err instanceof Error ? err : new Error(VERIFY_OVERRIDE_MSG);
|
|
465
|
+
console.warn(VERIFY_OVERRIDE_MSG, err);
|
|
419
466
|
return false;
|
|
420
467
|
}
|
|
421
468
|
}
|
|
@@ -437,11 +484,12 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
437
484
|
}
|
|
438
485
|
if ([...filtered.keys()].length) request = filtered;
|
|
439
486
|
}
|
|
487
|
+
const headerInit = res.headers ? headersInitToHeaders(res.headers) : void 0;
|
|
440
488
|
return {
|
|
441
489
|
kind: "continue",
|
|
442
490
|
request,
|
|
443
|
-
responseHeaders:
|
|
444
|
-
cookies: /* @__PURE__ */ new Map()
|
|
491
|
+
responseHeaders: headerInit ? responseHeaderItems(headerInit) : /* @__PURE__ */ new Map(),
|
|
492
|
+
cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
|
|
445
493
|
};
|
|
446
494
|
}
|
|
447
495
|
if (res.headers.get("x-middleware-next") === "1") {
|
|
@@ -485,16 +533,57 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
|
|
|
485
533
|
const cookies = mergeWrites(cookieWrites, cookieStrategy, (key, winner, loser) => {
|
|
486
534
|
if (debug) logger.debug({ cookie: key, winner, loser }, "cookie conflict resolved");
|
|
487
535
|
});
|
|
488
|
-
|
|
536
|
+
const seenHeaders = /* @__PURE__ */ new Set();
|
|
537
|
+
for (const write of headerWrites) {
|
|
538
|
+
for (const key of write.items.keys()) seenHeaders.add(key);
|
|
539
|
+
}
|
|
540
|
+
const dropHeaders = [];
|
|
541
|
+
for (const key of seenHeaders) {
|
|
542
|
+
if (!headers.has(key)) dropHeaders.push(key);
|
|
543
|
+
}
|
|
544
|
+
applyMergedToResponse(res, headers, cookies, dropHeaders);
|
|
489
545
|
return res;
|
|
490
546
|
}
|
|
491
547
|
|
|
548
|
+
// src/core/timeout.ts
|
|
549
|
+
var RuleTimeoutError = class extends Error {
|
|
550
|
+
ruleName;
|
|
551
|
+
timeoutMs;
|
|
552
|
+
constructor(ruleName, timeoutMs) {
|
|
553
|
+
super(`[proxy-chain] ${ruleName} timed out after ${timeoutMs}ms`);
|
|
554
|
+
this.name = "RuleTimeoutError";
|
|
555
|
+
this.ruleName = ruleName;
|
|
556
|
+
this.timeoutMs = timeoutMs;
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
function assertFiniteRuleTimeoutMs(ruleTimeoutMs) {
|
|
560
|
+
if (ruleTimeoutMs != null && !Number.isFinite(ruleTimeoutMs)) {
|
|
561
|
+
throw new RangeError(
|
|
562
|
+
`[proxy-chain] ruleTimeoutMs must be a finite positive number, got ${ruleTimeoutMs}`
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
async function withRuleTimeout(promise, timeoutMs, ruleName) {
|
|
567
|
+
assertFiniteRuleTimeoutMs(timeoutMs);
|
|
568
|
+
if (timeoutMs == null || timeoutMs <= 0) return promise;
|
|
569
|
+
let timer;
|
|
570
|
+
const timeout = new Promise((_, reject) => {
|
|
571
|
+
timer = setTimeout(() => reject(new RuleTimeoutError(ruleName, timeoutMs)), timeoutMs);
|
|
572
|
+
});
|
|
573
|
+
try {
|
|
574
|
+
return await Promise.race([promise, timeout]);
|
|
575
|
+
} finally {
|
|
576
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
577
|
+
void promise.catch(() => {
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
492
582
|
// src/core/engine.ts
|
|
493
|
-
import { NextRequest, NextResponse as NextResponse2 } from "next/server";
|
|
494
583
|
function isPathFilter(value) {
|
|
495
584
|
if (value === null || typeof value !== "object") return false;
|
|
496
585
|
if ("nextUrl" in value) return false;
|
|
497
|
-
return "include" in value || "exclude" in value || "name" in value
|
|
586
|
+
return "include" in value || "exclude" in value || "name" in value;
|
|
498
587
|
}
|
|
499
588
|
function defineProxy(nameOrRun, maybeRun) {
|
|
500
589
|
const defaultName = typeof nameOrRun === "string" ? nameOrRun : void 0;
|
|
@@ -514,25 +603,29 @@ function defineProxy(nameOrRun, maybeRun) {
|
|
|
514
603
|
});
|
|
515
604
|
return proxy;
|
|
516
605
|
}
|
|
517
|
-
function resolveConfig(overrides
|
|
518
|
-
const { logger, debug, ...rest } = overrides;
|
|
519
|
-
|
|
520
|
-
createContext:
|
|
606
|
+
function resolveConfig(overrides, fallbackCreateContext) {
|
|
607
|
+
const { logger, debug, createContext, ...rest } = overrides;
|
|
608
|
+
const config = {
|
|
609
|
+
createContext: createContext ?? fallbackCreateContext,
|
|
521
610
|
cookieMergeStrategy: "last-write-wins",
|
|
522
611
|
headerMergeStrategy: "last-write-wins",
|
|
523
612
|
debug: false,
|
|
524
613
|
ruleTimeoutMs: 0,
|
|
525
614
|
requestHeaderPolicy: {},
|
|
526
615
|
strictOverrideCheck: false,
|
|
616
|
+
hostFolderHeader: void 0,
|
|
527
617
|
...rest,
|
|
528
618
|
...debug !== void 0 ? { debug } : {},
|
|
529
619
|
logger: logger ?? createConsoleLogger(debug ? "debug" : "info")
|
|
530
620
|
};
|
|
621
|
+
assertFiniteRuleTimeoutMs(config.ruleTimeoutMs);
|
|
622
|
+
return config;
|
|
531
623
|
}
|
|
532
624
|
function proxyChain(optionsOrEntries, maybeEntries) {
|
|
533
625
|
const options = Array.isArray(optionsOrEntries) ? {} : optionsOrEntries;
|
|
534
|
-
const entries = Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries;
|
|
535
|
-
const
|
|
626
|
+
const entries = (Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries) ?? [];
|
|
627
|
+
const fallbackCreateContext = createProxyContext;
|
|
628
|
+
const config = resolveConfig(options, fallbackCreateContext);
|
|
536
629
|
const rules = entries.map(toRule);
|
|
537
630
|
const {
|
|
538
631
|
logger,
|
|
@@ -541,7 +634,8 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
541
634
|
headerMergeStrategy,
|
|
542
635
|
ruleTimeoutMs,
|
|
543
636
|
requestHeaderPolicy,
|
|
544
|
-
strictOverrideCheck
|
|
637
|
+
strictOverrideCheck,
|
|
638
|
+
hostFolderHeader
|
|
545
639
|
} = config;
|
|
546
640
|
assertOverrideMechanismSupported(strictOverrideCheck);
|
|
547
641
|
for (let i = 0; i < rules.length; i++) {
|
|
@@ -607,7 +701,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
607
701
|
if (config.onError) {
|
|
608
702
|
try {
|
|
609
703
|
const recovered = await config.onError(err, i, activeReq, ctx);
|
|
610
|
-
if (recovered == null)
|
|
704
|
+
if (recovered == null) return safeInternalError();
|
|
611
705
|
if (isNextResult(recovered)) {
|
|
612
706
|
raw = recovered;
|
|
613
707
|
} else if (recovered instanceof Response) {
|
|
@@ -646,7 +740,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
646
740
|
debug
|
|
647
741
|
);
|
|
648
742
|
} else {
|
|
649
|
-
|
|
743
|
+
return safeInternalError();
|
|
650
744
|
}
|
|
651
745
|
} catch (onErrorErr) {
|
|
652
746
|
logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
|
|
@@ -662,6 +756,9 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
662
756
|
if (outcome.kind === "continue") {
|
|
663
757
|
if (outcome.rewriteUrl) {
|
|
664
758
|
pendingRewriteUrl = outcome.rewriteUrl;
|
|
759
|
+
if (currentReq === req) {
|
|
760
|
+
currentReq = new NextRequest(currentReq);
|
|
761
|
+
}
|
|
665
762
|
try {
|
|
666
763
|
const parsed = new URL(outcome.rewriteUrl);
|
|
667
764
|
currentReq.nextUrl.pathname = parsed.pathname;
|
|
@@ -714,24 +811,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
714
811
|
})
|
|
715
812
|
);
|
|
716
813
|
}
|
|
717
|
-
const internalFolder = appliedRequestOverrides.get(
|
|
814
|
+
const internalFolder = hostFolderHeader ? appliedRequestOverrides.get(hostFolderHeader) : null;
|
|
718
815
|
if (internalFolder && outcome.response.headers.has("x-middleware-rewrite")) {
|
|
719
816
|
const rawRewrite = outcome.response.headers.get("x-middleware-rewrite");
|
|
720
|
-
const cleanFolder =
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
outcome.response.headers.set("x-middleware-rewrite", parsed.toString());
|
|
726
|
-
}
|
|
727
|
-
} catch {
|
|
728
|
-
if (!rawRewrite.startsWith(cleanFolder)) {
|
|
729
|
-
outcome.response.headers.set(
|
|
730
|
-
"x-middleware-rewrite",
|
|
731
|
-
cleanFolder + (rawRewrite === "/" ? "" : rawRewrite)
|
|
732
|
-
);
|
|
733
|
-
}
|
|
734
|
-
}
|
|
817
|
+
const cleanFolder = physicalFolderPrefix(internalFolder);
|
|
818
|
+
outcome.response.headers.set(
|
|
819
|
+
"x-middleware-rewrite",
|
|
820
|
+
applyFolderPrefix(rawRewrite, cleanFolder, currentReq.url)
|
|
821
|
+
);
|
|
735
822
|
}
|
|
736
823
|
return finalizeResponse(
|
|
737
824
|
outcome.response,
|
|
@@ -744,22 +831,12 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
744
831
|
);
|
|
745
832
|
}
|
|
746
833
|
const finalReq = materializeRequest();
|
|
747
|
-
const internalHostFolder = appliedRequestOverrides.get(
|
|
834
|
+
const internalHostFolder = hostFolderHeader ? appliedRequestOverrides.get(hostFolderHeader) : null;
|
|
748
835
|
let finalRewriteUrl = pendingRewriteUrl;
|
|
749
836
|
if (internalHostFolder) {
|
|
750
|
-
const cleanFolder =
|
|
837
|
+
const cleanFolder = physicalFolderPrefix(internalHostFolder);
|
|
751
838
|
if (finalRewriteUrl) {
|
|
752
|
-
|
|
753
|
-
const parsed = new URL(finalRewriteUrl, finalReq.url);
|
|
754
|
-
if (!parsed.pathname.startsWith(cleanFolder)) {
|
|
755
|
-
parsed.pathname = cleanFolder + (parsed.pathname === "/" ? "" : parsed.pathname);
|
|
756
|
-
finalRewriteUrl = parsed.toString();
|
|
757
|
-
}
|
|
758
|
-
} catch {
|
|
759
|
-
if (!finalRewriteUrl.startsWith(cleanFolder)) {
|
|
760
|
-
finalRewriteUrl = cleanFolder + (finalRewriteUrl === "/" ? "" : finalRewriteUrl);
|
|
761
|
-
}
|
|
762
|
-
}
|
|
839
|
+
finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
|
|
763
840
|
} else {
|
|
764
841
|
const currentPath = finalReq.nextUrl.pathname;
|
|
765
842
|
if (!currentPath.startsWith(cleanFolder)) {
|
|
@@ -799,42 +876,12 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
799
876
|
};
|
|
800
877
|
}
|
|
801
878
|
export {
|
|
802
|
-
DEFAULT_BLOCKED_REQUEST_HEADERS,
|
|
803
|
-
NEXT,
|
|
804
879
|
RuleTimeoutError,
|
|
805
|
-
applyMergedToResponse,
|
|
806
|
-
assertIncludeExcludeNoOverlap,
|
|
807
|
-
assertOverrideMechanismSupported,
|
|
808
|
-
compileScopes,
|
|
809
|
-
cookieItemsFromHeaders,
|
|
810
|
-
createConsoleLogger,
|
|
811
880
|
createProxyContext,
|
|
812
|
-
decodeOverriddenRequestHeaders,
|
|
813
881
|
defineProxy,
|
|
814
|
-
finalizeResponse,
|
|
815
|
-
formatPipelineLine,
|
|
816
|
-
headersDiffer,
|
|
817
|
-
headersInitToHeaders,
|
|
818
882
|
host,
|
|
819
883
|
isNextResult,
|
|
820
|
-
isRequestHeaderAllowed,
|
|
821
|
-
listSetCookie,
|
|
822
|
-
mergeRequestHeaderOverrides,
|
|
823
|
-
mergeWrites,
|
|
824
884
|
next,
|
|
825
|
-
normalizeHost,
|
|
826
|
-
parseCookieName,
|
|
827
885
|
path,
|
|
828
|
-
|
|
829
|
-
proxyChain,
|
|
830
|
-
resolveRuleResult,
|
|
831
|
-
responseHeaderItems,
|
|
832
|
-
ruleLabel,
|
|
833
|
-
ruleMatches,
|
|
834
|
-
safeInternalError,
|
|
835
|
-
toPathRegex,
|
|
836
|
-
toRule,
|
|
837
|
-
toStatelessRegExp,
|
|
838
|
-
withPaths,
|
|
839
|
-
withRuleTimeout
|
|
886
|
+
proxyChain
|
|
840
887
|
};
|