@klnap/next-proxy-chain 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +126 -0
- package/dist/chunk-PTAOIFNB.js +412 -0
- package/dist/core.cjs +467 -0
- package/dist/core.d.cts +210 -0
- package/dist/core.d.ts +210 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +68 -0
- package/dist/core.js.map +1 -0
- package/dist/index.cjs +882 -0
- package/dist/index.d.cts +65 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +478 -0
- package/dist/index.js.map +1 -0
- package/package.json +61 -0
package/dist/core.cjs
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/core.ts
|
|
21
|
+
var core_exports = {};
|
|
22
|
+
__export(core_exports, {
|
|
23
|
+
DEFAULT_BLOCKED_REQUEST_HEADERS: () => DEFAULT_BLOCKED_REQUEST_HEADERS,
|
|
24
|
+
NEXT: () => NEXT,
|
|
25
|
+
RuleTimeoutError: () => RuleTimeoutError,
|
|
26
|
+
applyMergedToResponse: () => applyMergedToResponse,
|
|
27
|
+
assertIncludeExcludeNoOverlap: () => assertIncludeExcludeNoOverlap,
|
|
28
|
+
compileScopes: () => compileScopes,
|
|
29
|
+
cookieItemsFromHeaders: () => cookieItemsFromHeaders,
|
|
30
|
+
createConsoleLogger: () => createConsoleLogger,
|
|
31
|
+
createProxyContext: () => createProxyContext,
|
|
32
|
+
decodeOverriddenRequestHeaders: () => decodeOverriddenRequestHeaders,
|
|
33
|
+
formatPipelineLine: () => formatPipelineLine,
|
|
34
|
+
headersDiffer: () => headersDiffer,
|
|
35
|
+
headersInitToHeaders: () => headersInitToHeaders,
|
|
36
|
+
host: () => host,
|
|
37
|
+
isNextResult: () => isNextResult,
|
|
38
|
+
isRequestHeaderAllowed: () => isRequestHeaderAllowed,
|
|
39
|
+
listSetCookie: () => listSetCookie,
|
|
40
|
+
mergeRequestHeaderOverrides: () => mergeRequestHeaderOverrides,
|
|
41
|
+
mergeWrites: () => mergeWrites,
|
|
42
|
+
next: () => next,
|
|
43
|
+
normalizeHost: () => normalizeHost,
|
|
44
|
+
parseCookieName: () => parseCookieName,
|
|
45
|
+
path: () => path,
|
|
46
|
+
pathMatches: () => pathMatches,
|
|
47
|
+
responseHeaderItems: () => responseHeaderItems,
|
|
48
|
+
ruleLabel: () => ruleLabel,
|
|
49
|
+
ruleMatches: () => ruleMatches,
|
|
50
|
+
toPathRegex: () => toPathRegex,
|
|
51
|
+
toRule: () => toRule,
|
|
52
|
+
toStatelessRegExp: () => toStatelessRegExp,
|
|
53
|
+
withPaths: () => withPaths,
|
|
54
|
+
withRuleTimeout: () => withRuleTimeout
|
|
55
|
+
});
|
|
56
|
+
module.exports = __toCommonJS(core_exports);
|
|
57
|
+
var NEXT = /* @__PURE__ */ Symbol.for("proxy-chain.next");
|
|
58
|
+
function next(options = {}) {
|
|
59
|
+
return { [NEXT]: true, ...options };
|
|
60
|
+
}
|
|
61
|
+
function isNextResult(value) {
|
|
62
|
+
return typeof value === "object" && value !== null && NEXT in value;
|
|
63
|
+
}
|
|
64
|
+
function createProxyContext() {
|
|
65
|
+
return /* @__PURE__ */ new Map();
|
|
66
|
+
}
|
|
67
|
+
var USELESS_FN_NAMES = /* @__PURE__ */ new Set(["", "proxy", "anonymous", "run", "next"]);
|
|
68
|
+
function usefulName(value) {
|
|
69
|
+
if (!value || USELESS_FN_NAMES.has(value)) return void 0;
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
function toStatelessRegExp(re) {
|
|
73
|
+
const flags = re.flags.replace(/[gy]/g, "");
|
|
74
|
+
return flags === re.flags ? re : new RegExp(re.source, flags);
|
|
75
|
+
}
|
|
76
|
+
function escapeRegex(value) {
|
|
77
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
78
|
+
}
|
|
79
|
+
function host(matcher) {
|
|
80
|
+
const list = Array.isArray(matcher) ? matcher : [matcher];
|
|
81
|
+
const parts = list.map((m) => {
|
|
82
|
+
if (m instanceof RegExp) return `(?:${toStatelessRegExp(m).source})`;
|
|
83
|
+
return `(?:${escapeRegex(m.toLowerCase())})`;
|
|
84
|
+
});
|
|
85
|
+
return toStatelessRegExp(new RegExp(`^(?:${parts.join("|")})$`, "i"));
|
|
86
|
+
}
|
|
87
|
+
function isScopeObject(value) {
|
|
88
|
+
return "host" in value || "path" in value;
|
|
89
|
+
}
|
|
90
|
+
function compileScopes(input, pathOptions) {
|
|
91
|
+
if (input == null) return void 0;
|
|
92
|
+
const list = Array.isArray(input) ? input : [input];
|
|
93
|
+
const compilePath = (matcher) => {
|
|
94
|
+
if (Array.isArray(matcher)) {
|
|
95
|
+
const parts = matcher.map(
|
|
96
|
+
(m) => typeof m === "string" ? path(m, pathOptions) : toStatelessRegExp(m)
|
|
97
|
+
);
|
|
98
|
+
if (parts.length === 1) return parts[0];
|
|
99
|
+
return toStatelessRegExp(new RegExp(`(?:${parts.map((r) => `(?:${r.source})`).join("|")})`));
|
|
100
|
+
}
|
|
101
|
+
return typeof matcher === "string" ? path(matcher, pathOptions) : toStatelessRegExp(matcher);
|
|
102
|
+
};
|
|
103
|
+
const compiled = [];
|
|
104
|
+
for (const item of list) {
|
|
105
|
+
if (typeof item === "string" || item instanceof RegExp) {
|
|
106
|
+
compiled.push({ path: compilePath(item) });
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (item && typeof item === "object" && isScopeObject(item)) {
|
|
110
|
+
if (item.host == null && item.path == null) {
|
|
111
|
+
throw new Error("[proxy-chain] scope needs at least `host` or `path`");
|
|
112
|
+
}
|
|
113
|
+
compiled.push({
|
|
114
|
+
host: item.host != null ? host(item.host) : void 0,
|
|
115
|
+
path: item.path != null ? compilePath(item.path) : void 0
|
|
116
|
+
});
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
throw new Error("[proxy-chain] invalid include/exclude scope");
|
|
120
|
+
}
|
|
121
|
+
return compiled;
|
|
122
|
+
}
|
|
123
|
+
function scopeMatches(pathname, hostname, scope) {
|
|
124
|
+
if (scope.host) {
|
|
125
|
+
if (!hostname || !scope.host.test(hostname)) return false;
|
|
126
|
+
}
|
|
127
|
+
if (scope.path) {
|
|
128
|
+
if (!scope.path.test(pathname)) return false;
|
|
129
|
+
}
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
function toRule(entry) {
|
|
133
|
+
if (typeof entry === "function") {
|
|
134
|
+
const name2 = usefulName(entry.name);
|
|
135
|
+
return name2 ? { run: entry, name: name2 } : { run: entry };
|
|
136
|
+
}
|
|
137
|
+
const rule = entry;
|
|
138
|
+
const runName = typeof rule.run === "function" ? usefulName(rule.run.name) : void 0;
|
|
139
|
+
const name = usefulName(rule.name) ?? runName;
|
|
140
|
+
const harden = (scopes) => scopes?.map((s) => ({
|
|
141
|
+
host: s.host ? toStatelessRegExp(s.host) : void 0,
|
|
142
|
+
path: s.path ? toStatelessRegExp(s.path) : void 0
|
|
143
|
+
}));
|
|
144
|
+
return {
|
|
145
|
+
...rule,
|
|
146
|
+
name: name ?? void 0,
|
|
147
|
+
include: harden(rule.include),
|
|
148
|
+
exclude: harden(rule.exclude)
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function ruleLabel(rule, index) {
|
|
152
|
+
const runName = typeof rule.run === "function" ? usefulName(rule.run.name) : void 0;
|
|
153
|
+
return usefulName(rule.name) ?? runName ?? `rule#${index}`;
|
|
154
|
+
}
|
|
155
|
+
function withPaths(entry, filter) {
|
|
156
|
+
const base = toRule(entry);
|
|
157
|
+
const opts = filter.pathOptions;
|
|
158
|
+
const include = compileScopes(filter.include, opts);
|
|
159
|
+
const exclude = compileScopes(filter.exclude, opts);
|
|
160
|
+
const name = filter.name ?? base.name;
|
|
161
|
+
assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
|
|
162
|
+
return { run: base.run, include, exclude, name };
|
|
163
|
+
}
|
|
164
|
+
function ruleMatches(pathname, hostname, rule) {
|
|
165
|
+
if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) return false;
|
|
166
|
+
if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
function pathMatches(pathname, rule) {
|
|
172
|
+
return ruleMatches(pathname, null, rule);
|
|
173
|
+
}
|
|
174
|
+
function normalizeHost(raw) {
|
|
175
|
+
if (!raw) return null;
|
|
176
|
+
const first = raw.split(",")[0]?.trim().toLowerCase();
|
|
177
|
+
if (!first) return null;
|
|
178
|
+
if (first.startsWith("[")) {
|
|
179
|
+
const end = first.indexOf("]");
|
|
180
|
+
return end === -1 ? first : first.slice(1, end);
|
|
181
|
+
}
|
|
182
|
+
const withoutPort = first.replace(/:\d+$/, "");
|
|
183
|
+
return withoutPort || null;
|
|
184
|
+
}
|
|
185
|
+
function parseCookieName(setCookie) {
|
|
186
|
+
const eq = setCookie.indexOf("=");
|
|
187
|
+
return (eq === -1 ? setCookie : setCookie.slice(0, eq)).trim();
|
|
188
|
+
}
|
|
189
|
+
function listSetCookie(headers) {
|
|
190
|
+
const extended = headers;
|
|
191
|
+
if (typeof extended.getSetCookie === "function") return extended.getSetCookie();
|
|
192
|
+
const single = headers.get("set-cookie");
|
|
193
|
+
return single ? [single] : [];
|
|
194
|
+
}
|
|
195
|
+
function cookieItemsFromHeaders(headers) {
|
|
196
|
+
const map = /* @__PURE__ */ new Map();
|
|
197
|
+
for (const value of listSetCookie(headers)) {
|
|
198
|
+
map.set(parseCookieName(value), value);
|
|
199
|
+
}
|
|
200
|
+
return map;
|
|
201
|
+
}
|
|
202
|
+
function responseHeaderItems(headers) {
|
|
203
|
+
const map = /* @__PURE__ */ new Map();
|
|
204
|
+
headers.forEach((value, key) => {
|
|
205
|
+
const lower = key.toLowerCase();
|
|
206
|
+
if (lower === "set-cookie") return;
|
|
207
|
+
if (lower.startsWith("x-middleware-next") || lower.startsWith("x-middleware-rewrite") || lower.startsWith("x-middleware-override-headers") || lower.startsWith("x-middleware-request-")) {
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
map.set(key, value);
|
|
211
|
+
});
|
|
212
|
+
return map;
|
|
213
|
+
}
|
|
214
|
+
function decodeOverriddenRequestHeaders(headers) {
|
|
215
|
+
const result = new Headers();
|
|
216
|
+
const overrideHeaderNames = headers.get("x-middleware-override-headers");
|
|
217
|
+
if (overrideHeaderNames) {
|
|
218
|
+
for (const name of overrideHeaderNames.split(",")) {
|
|
219
|
+
const trimmed = name.trim();
|
|
220
|
+
const val = headers.get(`x-middleware-request-${trimmed}`);
|
|
221
|
+
if (val !== null) {
|
|
222
|
+
result.set(trimmed, val);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return result;
|
|
227
|
+
}
|
|
228
|
+
function mergeWrites(writes, strategy, onConflict) {
|
|
229
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
230
|
+
const setBy = /* @__PURE__ */ new Map();
|
|
231
|
+
for (const write of writes) {
|
|
232
|
+
for (const [key, value] of write.items) {
|
|
233
|
+
const existing = resolved.get(key);
|
|
234
|
+
if (existing === void 0) {
|
|
235
|
+
resolved.set(key, value);
|
|
236
|
+
setBy.set(key, write.ruleName);
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const previousRule = setBy.get(key);
|
|
240
|
+
if (typeof strategy === "function") {
|
|
241
|
+
const result = strategy(key, existing, value);
|
|
242
|
+
if (result === null) resolved.delete(key);
|
|
243
|
+
else resolved.set(key, result);
|
|
244
|
+
setBy.set(key, write.ruleName);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (strategy === "first-write-wins") {
|
|
248
|
+
onConflict?.(key, previousRule, write.ruleName);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
onConflict?.(key, write.ruleName, previousRule);
|
|
252
|
+
resolved.set(key, value);
|
|
253
|
+
setBy.set(key, write.ruleName);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return resolved;
|
|
257
|
+
}
|
|
258
|
+
function applyMergedToResponse(res, headers, cookies) {
|
|
259
|
+
for (const [key, value] of headers) {
|
|
260
|
+
res.headers.set(key, value);
|
|
261
|
+
}
|
|
262
|
+
res.headers.delete("set-cookie");
|
|
263
|
+
for (const cookie of cookies.values()) {
|
|
264
|
+
res.headers.append("set-cookie", cookie);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
var DEFAULT_BLOCKED_REQUEST_HEADERS = [
|
|
268
|
+
"host",
|
|
269
|
+
"connection",
|
|
270
|
+
"keep-alive",
|
|
271
|
+
"proxy-authenticate",
|
|
272
|
+
"proxy-authorization",
|
|
273
|
+
"te",
|
|
274
|
+
"trailer",
|
|
275
|
+
"transfer-encoding",
|
|
276
|
+
"upgrade",
|
|
277
|
+
"content-length",
|
|
278
|
+
"cookie",
|
|
279
|
+
"authorization",
|
|
280
|
+
"x-forwarded-host",
|
|
281
|
+
"x-forwarded-for",
|
|
282
|
+
"x-forwarded-proto",
|
|
283
|
+
"x-real-ip",
|
|
284
|
+
"x-middleware-next",
|
|
285
|
+
"x-middleware-override-headers"
|
|
286
|
+
];
|
|
287
|
+
function normalizeHeaderName(name) {
|
|
288
|
+
return name.toLowerCase();
|
|
289
|
+
}
|
|
290
|
+
function isRequestHeaderAllowed(name, policy = {}) {
|
|
291
|
+
const key = normalizeHeaderName(name);
|
|
292
|
+
const allowed = new Set((policy.allowed ?? []).map(normalizeHeaderName));
|
|
293
|
+
if (allowed.has(key)) return true;
|
|
294
|
+
if (key.startsWith("x-middleware-")) return false;
|
|
295
|
+
const blocked = /* @__PURE__ */ new Set([
|
|
296
|
+
...DEFAULT_BLOCKED_REQUEST_HEADERS.map(normalizeHeaderName),
|
|
297
|
+
...(policy.blocked ?? []).map(normalizeHeaderName)
|
|
298
|
+
]);
|
|
299
|
+
return !blocked.has(key);
|
|
300
|
+
}
|
|
301
|
+
function mergeRequestHeaderOverrides(target, overrides, policy = {}) {
|
|
302
|
+
const dropped = [];
|
|
303
|
+
let applied = 0;
|
|
304
|
+
overrides.forEach((value, key) => {
|
|
305
|
+
if (!isRequestHeaderAllowed(key, policy)) {
|
|
306
|
+
dropped.push(key);
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
target.set(key, value);
|
|
310
|
+
applied++;
|
|
311
|
+
});
|
|
312
|
+
return { applied, dropped };
|
|
313
|
+
}
|
|
314
|
+
function headersInitToHeaders(init) {
|
|
315
|
+
return new Headers(init);
|
|
316
|
+
}
|
|
317
|
+
function headersDiffer(base, overrides) {
|
|
318
|
+
for (const [key, value] of overrides.entries()) {
|
|
319
|
+
if (base.get(key) !== value) return true;
|
|
320
|
+
}
|
|
321
|
+
return false;
|
|
322
|
+
}
|
|
323
|
+
function segmentToRegex(segment) {
|
|
324
|
+
if (segment === "**") return "(?:.*)";
|
|
325
|
+
if (segment === "*") return "[^/]+";
|
|
326
|
+
if (segment.startsWith(":")) return "[^/]+";
|
|
327
|
+
return escapeRegex(segment);
|
|
328
|
+
}
|
|
329
|
+
function path(pattern, options = {}) {
|
|
330
|
+
const { locales = [] } = options;
|
|
331
|
+
const localePrefix = locales.length > 0 ? `(?:(?:${locales.map(escapeRegex).join("|")})\\/)?` : "";
|
|
332
|
+
if (pattern instanceof RegExp) {
|
|
333
|
+
const body2 = pattern.source.replace(/^\^/, "").replace(/\$$/, "");
|
|
334
|
+
const needsStart = !pattern.source.startsWith("^");
|
|
335
|
+
const needsEnd = !pattern.source.endsWith("$");
|
|
336
|
+
return toStatelessRegExp(
|
|
337
|
+
new RegExp(
|
|
338
|
+
`${needsStart ? "^" : ""}${localePrefix ? `/${localePrefix}` : ""}${body2}${needsEnd ? "$" : ""}`,
|
|
339
|
+
pattern.flags
|
|
340
|
+
)
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
|
|
344
|
+
const segments = normalized.slice(1).split("/");
|
|
345
|
+
const trailingStar = segments.length > 0 && segments[segments.length - 1] === "*";
|
|
346
|
+
const suffix = trailingStar ? "(?:\\/.*)?$" : "$";
|
|
347
|
+
const body = trailingStar ? segments.slice(0, -1).map(segmentToRegex).concat("[^/]+").join("\\/") : segments.map(segmentToRegex).join("\\/");
|
|
348
|
+
return new RegExp(`^/${localePrefix}${body}${suffix}`);
|
|
349
|
+
}
|
|
350
|
+
function toPathRegex(matcher, options) {
|
|
351
|
+
const list = Array.isArray(matcher) ? matcher : [matcher];
|
|
352
|
+
const regexes = list.map((m) => path(m, options));
|
|
353
|
+
if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
|
|
354
|
+
return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
|
|
355
|
+
}
|
|
356
|
+
function scopeKey(scope) {
|
|
357
|
+
return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
|
|
358
|
+
}
|
|
359
|
+
function assertIncludeExcludeNoOverlap(include, exclude, label) {
|
|
360
|
+
if (!include?.length || !exclude?.length) return;
|
|
361
|
+
const excluded = new Set(exclude.map(scopeKey));
|
|
362
|
+
for (const scope of include) {
|
|
363
|
+
if (excluded.has(scopeKey(scope))) {
|
|
364
|
+
throw new Error(
|
|
365
|
+
`[proxy-chain] ${label}: include and exclude share an identical scope. Remove one.`
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
var LEVEL_RANK = {
|
|
371
|
+
debug: 10,
|
|
372
|
+
info: 20,
|
|
373
|
+
warn: 30,
|
|
374
|
+
error: 40
|
|
375
|
+
};
|
|
376
|
+
function createConsoleLogger(minLevel = "info") {
|
|
377
|
+
const min = LEVEL_RANK[minLevel];
|
|
378
|
+
const write = (level) => (obj, msg) => {
|
|
379
|
+
if (LEVEL_RANK[level] < min) return;
|
|
380
|
+
if (typeof obj === "string") {
|
|
381
|
+
console[level](obj);
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const message = msg ?? "";
|
|
385
|
+
if (message) console[level](`[proxy-chain] ${message}`, obj);
|
|
386
|
+
else console[level]("[proxy-chain]", obj);
|
|
387
|
+
};
|
|
388
|
+
return {
|
|
389
|
+
debug: write("debug"),
|
|
390
|
+
info: write("info"),
|
|
391
|
+
warn: write("warn"),
|
|
392
|
+
error: write("error")
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
function formatDuration(ms) {
|
|
396
|
+
return `${ms.toFixed(2)}ms`;
|
|
397
|
+
}
|
|
398
|
+
function formatPipelineLine(input) {
|
|
399
|
+
const trace = input.traceId ? ` [${input.traceId.slice(0, 8)}]` : "";
|
|
400
|
+
const req = `${input.method} ${input.path}${trace}`;
|
|
401
|
+
const { name, outcome } = input;
|
|
402
|
+
switch (outcome.kind) {
|
|
403
|
+
case "passed":
|
|
404
|
+
return `[proxy-chain] \xB7 ${req} | ${name} (${formatDuration(outcome.duration)}) -> passed`;
|
|
405
|
+
case "next":
|
|
406
|
+
return `[proxy-chain] ~ ${req} | ${name} (${formatDuration(outcome.duration)}) -> headers mutated (${outcome.headers})`;
|
|
407
|
+
case "stop":
|
|
408
|
+
return `[proxy-chain] \xD7 ${req} | ${name} (${formatDuration(outcome.duration)}) -> stop ${outcome.status}`;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
var RuleTimeoutError = class extends Error {
|
|
412
|
+
ruleName;
|
|
413
|
+
timeoutMs;
|
|
414
|
+
constructor(ruleName, timeoutMs) {
|
|
415
|
+
super(`[proxy-chain] ${ruleName} timed out after ${timeoutMs}ms`);
|
|
416
|
+
this.name = "RuleTimeoutError";
|
|
417
|
+
this.ruleName = ruleName;
|
|
418
|
+
this.timeoutMs = timeoutMs;
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
async function withRuleTimeout(promise, timeoutMs, ruleName) {
|
|
422
|
+
if (!timeoutMs || timeoutMs <= 0) return promise;
|
|
423
|
+
let timer;
|
|
424
|
+
const timeout = new Promise((_, reject) => {
|
|
425
|
+
timer = setTimeout(() => reject(new RuleTimeoutError(ruleName, timeoutMs)), timeoutMs);
|
|
426
|
+
});
|
|
427
|
+
try {
|
|
428
|
+
return await Promise.race([promise, timeout]);
|
|
429
|
+
} finally {
|
|
430
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
434
|
+
0 && (module.exports = {
|
|
435
|
+
DEFAULT_BLOCKED_REQUEST_HEADERS,
|
|
436
|
+
NEXT,
|
|
437
|
+
RuleTimeoutError,
|
|
438
|
+
applyMergedToResponse,
|
|
439
|
+
assertIncludeExcludeNoOverlap,
|
|
440
|
+
compileScopes,
|
|
441
|
+
cookieItemsFromHeaders,
|
|
442
|
+
createConsoleLogger,
|
|
443
|
+
createProxyContext,
|
|
444
|
+
decodeOverriddenRequestHeaders,
|
|
445
|
+
formatPipelineLine,
|
|
446
|
+
headersDiffer,
|
|
447
|
+
headersInitToHeaders,
|
|
448
|
+
host,
|
|
449
|
+
isNextResult,
|
|
450
|
+
isRequestHeaderAllowed,
|
|
451
|
+
listSetCookie,
|
|
452
|
+
mergeRequestHeaderOverrides,
|
|
453
|
+
mergeWrites,
|
|
454
|
+
next,
|
|
455
|
+
normalizeHost,
|
|
456
|
+
parseCookieName,
|
|
457
|
+
path,
|
|
458
|
+
pathMatches,
|
|
459
|
+
responseHeaderItems,
|
|
460
|
+
ruleLabel,
|
|
461
|
+
ruleMatches,
|
|
462
|
+
toPathRegex,
|
|
463
|
+
toRule,
|
|
464
|
+
toStatelessRegExp,
|
|
465
|
+
withPaths,
|
|
466
|
+
withRuleTimeout
|
|
467
|
+
});
|
package/dist/core.d.cts
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Platform-agnostic proxy-chain primitives.
|
|
3
|
+
* No Next.js imports — unit-testable on any Web API runtime.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Brand for an explicit "continue the chain" action.
|
|
7
|
+
* Mirrors the mental model of middleware `next()`, without relying on
|
|
8
|
+
* Next.js private response headers.
|
|
9
|
+
*/
|
|
10
|
+
declare const NEXT: unique symbol;
|
|
11
|
+
type NextOptions = {
|
|
12
|
+
/** Request header overrides visible to later rules and the final handler. */
|
|
13
|
+
request?: HeadersInit;
|
|
14
|
+
/** Response headers merged into the eventual outgoing response (last-write-wins). */
|
|
15
|
+
headers?: HeadersInit;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Continue the pipeline. Prefer this over returning a framework `NextResponse.next()`.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* return next({ request: { "x-request-id": id }, headers: { "x-request-id": id } })
|
|
22
|
+
*/
|
|
23
|
+
type NextResult = NextOptions & {
|
|
24
|
+
readonly [NEXT]: true;
|
|
25
|
+
};
|
|
26
|
+
declare function next(options?: NextOptions): NextResult;
|
|
27
|
+
declare function isNextResult(value: unknown): value is NextResult;
|
|
28
|
+
/**
|
|
29
|
+
* Shared state for one request. `Map` avoids prototype-poisoning risks that
|
|
30
|
+
* come with plain objects and attacker-controlled keys.
|
|
31
|
+
*/
|
|
32
|
+
type ProxyContext = Map<string, unknown>;
|
|
33
|
+
declare function createProxyContext(): ProxyContext;
|
|
34
|
+
type ProxyResult<TResponse> = TResponse | NextResult | undefined | void;
|
|
35
|
+
type PathMatcher = RegExp | string;
|
|
36
|
+
type PathOptions = {
|
|
37
|
+
/** Optional locale prefixes, e.g. next-intl `as-needed` routes. */
|
|
38
|
+
locales?: readonly string[];
|
|
39
|
+
};
|
|
40
|
+
type HostMatcher = string | RegExp | readonly (string | RegExp)[];
|
|
41
|
+
/**
|
|
42
|
+
* One include/exclude clause.
|
|
43
|
+
*
|
|
44
|
+
* - `path("/admin/*")` — that path on **any** host
|
|
45
|
+
* - `{ host: "shop.localhost" }` — **any** path on that host
|
|
46
|
+
* - `{ host: "shop.localhost", path: "/checkout/*" }` — both must match
|
|
47
|
+
*
|
|
48
|
+
* Lists are OR. Exclude is checked before include and always wins.
|
|
49
|
+
*/
|
|
50
|
+
type RouteScopeInput = PathMatcher | {
|
|
51
|
+
host: HostMatcher;
|
|
52
|
+
path?: PathMatcher | PathMatcher[];
|
|
53
|
+
} | {
|
|
54
|
+
path: PathMatcher | PathMatcher[];
|
|
55
|
+
host?: HostMatcher;
|
|
56
|
+
};
|
|
57
|
+
type RouteScopeList = RouteScopeInput | RouteScopeInput[];
|
|
58
|
+
/** Compiled clause used at request time. Missing host/path means "any". */
|
|
59
|
+
type CompiledScope = {
|
|
60
|
+
host?: RegExp;
|
|
61
|
+
path?: RegExp;
|
|
62
|
+
};
|
|
63
|
+
interface BaseProxyRule<TFn> {
|
|
64
|
+
run: TFn;
|
|
65
|
+
include?: CompiledScope[];
|
|
66
|
+
exclude?: CompiledScope[];
|
|
67
|
+
name?: string;
|
|
68
|
+
}
|
|
69
|
+
type ProxyPathFilter = {
|
|
70
|
+
include?: RouteScopeList;
|
|
71
|
+
exclude?: RouteScopeList;
|
|
72
|
+
pathOptions?: PathOptions;
|
|
73
|
+
name?: string;
|
|
74
|
+
};
|
|
75
|
+
type Entry<TFn> = TFn | BaseProxyRule<TFn>;
|
|
76
|
+
/**
|
|
77
|
+
* Sticky RegExp flags (`g`, `y`) mutate `lastIndex` on each `.test()`.
|
|
78
|
+
* On Edge, one compiled pattern is shared across concurrent requests, so a
|
|
79
|
+
* sticky flag can make path matching flip between true/false spuriously.
|
|
80
|
+
* Always compile path filters without those flags.
|
|
81
|
+
*/
|
|
82
|
+
declare function toStatelessRegExp(re: RegExp): RegExp;
|
|
83
|
+
/**
|
|
84
|
+
* Build a host matcher RegExp from exact names and/or patterns.
|
|
85
|
+
* Exact strings are anchored; RegExp sources are OR-combined (sticky flags stripped).
|
|
86
|
+
*/
|
|
87
|
+
declare function host(matcher: HostMatcher): RegExp;
|
|
88
|
+
/**
|
|
89
|
+
* Compile user-facing include/exclude into stateless host/path clauses.
|
|
90
|
+
* Strings/globs go through `path()` (locale options apply). Raw RegExp is kept as-is
|
|
91
|
+
* (only sticky flags stripped) so prefix patterns like `/^\/admin/` keep working.
|
|
92
|
+
*/
|
|
93
|
+
declare function compileScopes(input: RouteScopeList | undefined, pathOptions?: PathOptions): CompiledScope[] | undefined;
|
|
94
|
+
declare function toRule<TFn>(entry: Entry<TFn>): BaseProxyRule<TFn>;
|
|
95
|
+
declare function ruleLabel<TFn>(rule: BaseProxyRule<TFn>, index: number): string;
|
|
96
|
+
/**
|
|
97
|
+
* Scope a rule with path/host filters.
|
|
98
|
+
*/
|
|
99
|
+
declare function withPaths<TFn>(entry: Entry<TFn>, filter: ProxyPathFilter): BaseProxyRule<TFn>;
|
|
100
|
+
/**
|
|
101
|
+
* Whether a rule applies to this request.
|
|
102
|
+
*
|
|
103
|
+
* Rules:
|
|
104
|
+
* 1. If any `exclude` clause matches -> skip (exclude wins).
|
|
105
|
+
* 2. If `include` is set -> run only when at least one clause matches (OR).
|
|
106
|
+
* 3. Path-only clauses apply to every host; host-only clauses apply to every path.
|
|
107
|
+
* 4. Mixing bare paths with host-scoped paths is not a conflict: OR widens the match.
|
|
108
|
+
*/
|
|
109
|
+
declare function ruleMatches<TFn>(pathname: string, hostname: string | null, rule: BaseProxyRule<TFn>): boolean;
|
|
110
|
+
/** Path-only helper for tests (host treated as unrestricted). */
|
|
111
|
+
declare function pathMatches<TFn>(pathname: string, rule: BaseProxyRule<TFn>): boolean;
|
|
112
|
+
/** Normalize `Host` / `X-Forwarded-Host` into a bare lowercase hostname (no port). */
|
|
113
|
+
declare function normalizeHost(raw: string | null | undefined): string | null;
|
|
114
|
+
declare function parseCookieName(setCookie: string): string;
|
|
115
|
+
/**
|
|
116
|
+
* Collect `Set-Cookie` entries. Prefer the multi-value `getSetCookie()` API;
|
|
117
|
+
* a single `get("set-cookie")` is only a last-resort fallback on older runtimes.
|
|
118
|
+
*/
|
|
119
|
+
declare function listSetCookie(headers: Headers): string[];
|
|
120
|
+
declare function cookieItemsFromHeaders(headers: Headers): Map<string, string>;
|
|
121
|
+
/**
|
|
122
|
+
* Response headers eligible for merge.
|
|
123
|
+
* Filters out `set-cookie` and internal Next.js middleware headers (`x-middleware-*`)
|
|
124
|
+
* to prevent leaking internal transport headers to client responses.
|
|
125
|
+
*/
|
|
126
|
+
declare function responseHeaderItems(headers: Headers): Map<string, string>;
|
|
127
|
+
/**
|
|
128
|
+
* Decode request header overrides encoded by Next.js `NextResponse.next({ request: { headers } })`.
|
|
129
|
+
*/
|
|
130
|
+
declare function decodeOverriddenRequestHeaders(headers: Headers): Headers;
|
|
131
|
+
interface EntryWrite {
|
|
132
|
+
ruleIndex: number;
|
|
133
|
+
ruleName: string;
|
|
134
|
+
items: Map<string, string>;
|
|
135
|
+
}
|
|
136
|
+
type MergeStrategy = "last-write-wins" | "first-write-wins" | ((key: string, existing: string, incoming: string) => string | null);
|
|
137
|
+
declare function mergeWrites(writes: EntryWrite[], strategy: MergeStrategy, onConflict?: (key: string, winner: string, loser: string) => void): Map<string, string>;
|
|
138
|
+
/**
|
|
139
|
+
* Apply merged headers and cookies onto the terminal response.
|
|
140
|
+
*
|
|
141
|
+
* Headers use last-write-wins via `set` (overwrite).
|
|
142
|
+
* Cookies are rebuilt from a name->value map so the same cookie never appears
|
|
143
|
+
* twice — browsers and CDNs behave unpredictably with duplicate Set-Cookie.
|
|
144
|
+
*/
|
|
145
|
+
declare function applyMergedToResponse(res: Response, headers: Map<string, string>, cookies: Map<string, string>): void;
|
|
146
|
+
/**
|
|
147
|
+
* Headers that must not be rewritten by a rule unless explicitly allow-listed.
|
|
148
|
+
* Covers hop-by-hop framing, identity, Next.js internal headers, and common trust headers.
|
|
149
|
+
*/
|
|
150
|
+
declare const DEFAULT_BLOCKED_REQUEST_HEADERS: readonly ["host", "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "content-length", "cookie", "authorization", "x-forwarded-host", "x-forwarded-for", "x-forwarded-proto", "x-real-ip", "x-middleware-next", "x-middleware-override-headers"];
|
|
151
|
+
type RequestHeaderPolicy = {
|
|
152
|
+
blocked?: readonly string[];
|
|
153
|
+
/** Opt-in exceptions to the block list (lower-case names). */
|
|
154
|
+
allowed?: readonly string[];
|
|
155
|
+
};
|
|
156
|
+
declare function isRequestHeaderAllowed(name: string, policy?: RequestHeaderPolicy): boolean;
|
|
157
|
+
declare function mergeRequestHeaderOverrides(target: Headers, overrides: Headers, policy?: RequestHeaderPolicy): {
|
|
158
|
+
applied: number;
|
|
159
|
+
dropped: string[];
|
|
160
|
+
};
|
|
161
|
+
declare function headersInitToHeaders(init?: HeadersInit): Headers;
|
|
162
|
+
declare function headersDiffer(base: Headers, overrides: Headers): boolean;
|
|
163
|
+
/**
|
|
164
|
+
* Build a stateless path matcher from a glob, param path, or RegExp.
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* path("/admin/*")
|
|
168
|
+
* path("/admin/:id")
|
|
169
|
+
* path("/admin/*", { locales: ["en", "pl"] })
|
|
170
|
+
*/
|
|
171
|
+
declare function path(pattern: string | RegExp, options?: PathOptions): RegExp;
|
|
172
|
+
declare function toPathRegex(matcher: PathMatcher | PathMatcher[], options?: PathOptions): RegExp;
|
|
173
|
+
/** Throw when the same clause appears in both include and exclude (always a no-op / footgun). */
|
|
174
|
+
declare function assertIncludeExcludeNoOverlap(include: CompiledScope[] | undefined, exclude: CompiledScope[] | undefined, label: string): void;
|
|
175
|
+
type LogLevel = "debug" | "info" | "warn" | "error";
|
|
176
|
+
interface ChainLogger {
|
|
177
|
+
debug: (obj: unknown, msg?: string) => void;
|
|
178
|
+
info: (obj: unknown, msg?: string) => void;
|
|
179
|
+
warn: (obj: unknown, msg?: string) => void;
|
|
180
|
+
error: (obj: unknown, msg?: string) => void;
|
|
181
|
+
}
|
|
182
|
+
declare function createConsoleLogger(minLevel?: LogLevel): ChainLogger;
|
|
183
|
+
type PipelineOutcome = {
|
|
184
|
+
kind: "passed";
|
|
185
|
+
duration: number;
|
|
186
|
+
} | {
|
|
187
|
+
kind: "next";
|
|
188
|
+
duration: number;
|
|
189
|
+
headers: number;
|
|
190
|
+
} | {
|
|
191
|
+
kind: "stop";
|
|
192
|
+
duration: number;
|
|
193
|
+
status: number;
|
|
194
|
+
};
|
|
195
|
+
/** One line per executed rule — method + path first so parallel Edge logs stay scannable. */
|
|
196
|
+
declare function formatPipelineLine(input: {
|
|
197
|
+
method: string;
|
|
198
|
+
path: string;
|
|
199
|
+
name: string;
|
|
200
|
+
traceId?: string;
|
|
201
|
+
outcome: PipelineOutcome;
|
|
202
|
+
}): string;
|
|
203
|
+
declare class RuleTimeoutError extends Error {
|
|
204
|
+
readonly ruleName: string;
|
|
205
|
+
readonly timeoutMs: number;
|
|
206
|
+
constructor(ruleName: string, timeoutMs: number);
|
|
207
|
+
}
|
|
208
|
+
declare function withRuleTimeout<T>(promise: Promise<T>, timeoutMs: number | undefined, ruleName: string): Promise<T>;
|
|
209
|
+
|
|
210
|
+
export { type BaseProxyRule, type ChainLogger, type CompiledScope, DEFAULT_BLOCKED_REQUEST_HEADERS, type EntryWrite, type HostMatcher, type LogLevel, type MergeStrategy, NEXT, type NextOptions, type NextResult, type PathMatcher, type PathOptions, type PipelineOutcome, type ProxyContext, type ProxyPathFilter, type ProxyResult, type RequestHeaderPolicy, type RouteScopeInput, type RouteScopeList, RuleTimeoutError, applyMergedToResponse, assertIncludeExcludeNoOverlap, compileScopes, cookieItemsFromHeaders, createConsoleLogger, createProxyContext, decodeOverriddenRequestHeaders, formatPipelineLine, headersDiffer, headersInitToHeaders, host, isNextResult, isRequestHeaderAllowed, listSetCookie, mergeRequestHeaderOverrides, mergeWrites, next, normalizeHost, parseCookieName, path, pathMatches, responseHeaderItems, ruleLabel, ruleMatches, toPathRegex, toRule, toStatelessRegExp, withPaths, withRuleTimeout };
|