@klnap/next-proxy-chain 2.0.0 → 3.0.1
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 +16 -0
- package/README.md +272 -205
- package/dist/index.cjs +89 -207
- package/dist/index.d.cts +34 -102
- package/dist/index.d.ts +34 -102
- package/dist/index.js +88 -201
- package/docs/api.md +190 -0
- package/docs/concepts.md +88 -0
- package/docs/guides.md +210 -0
- package/docs/security.md +104 -0
- package/llms.txt +17 -0
- package/package.json +7 -2
package/dist/index.js
CHANGED
|
@@ -1,35 +1,3 @@
|
|
|
1
|
-
// src/core/constants.ts
|
|
2
|
-
var NEXT = /* @__PURE__ */ Symbol.for("proxy-chain.next");
|
|
3
|
-
var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
|
|
4
|
-
"host",
|
|
5
|
-
"connection",
|
|
6
|
-
"keep-alive",
|
|
7
|
-
"proxy-authenticate",
|
|
8
|
-
"proxy-authorization",
|
|
9
|
-
"te",
|
|
10
|
-
"trailer",
|
|
11
|
-
"transfer-encoding",
|
|
12
|
-
"upgrade",
|
|
13
|
-
"content-length",
|
|
14
|
-
"cookie",
|
|
15
|
-
"authorization",
|
|
16
|
-
"x-forwarded-host",
|
|
17
|
-
"x-forwarded-for",
|
|
18
|
-
"x-forwarded-proto",
|
|
19
|
-
"x-real-ip",
|
|
20
|
-
"x-middleware-next",
|
|
21
|
-
"x-middleware-override-headers"
|
|
22
|
-
]);
|
|
23
|
-
var DEFINED_HANDLER = /* @__PURE__ */ Symbol.for("proxy-chain.defined-handler");
|
|
24
|
-
|
|
25
|
-
// src/core/actions.ts
|
|
26
|
-
function next(options = {}) {
|
|
27
|
-
return { [NEXT]: true, ...options };
|
|
28
|
-
}
|
|
29
|
-
function isNextResult(value) {
|
|
30
|
-
return typeof value === "object" && value !== null && NEXT in value;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
1
|
// src/core/engine.ts
|
|
34
2
|
import { NextRequest, NextResponse as NextResponse2 } from "next/server.js";
|
|
35
3
|
|
|
@@ -116,42 +84,12 @@ function createHandlerContext(metadata, applicationState, signal) {
|
|
|
116
84
|
}
|
|
117
85
|
|
|
118
86
|
// src/core/headers.ts
|
|
119
|
-
function normalizeHeaderName(name) {
|
|
120
|
-
return name.toLowerCase();
|
|
121
|
-
}
|
|
122
|
-
function headersInitToHeaders(init) {
|
|
123
|
-
return new Headers(init);
|
|
124
|
-
}
|
|
125
87
|
function headersDiffer(base, overrides) {
|
|
126
88
|
for (const [key, value] of overrides.entries()) {
|
|
127
89
|
if (base.get(key) !== value) return true;
|
|
128
90
|
}
|
|
129
91
|
return false;
|
|
130
92
|
}
|
|
131
|
-
function isRequestHeaderAllowed(name, policy = {}) {
|
|
132
|
-
const key = normalizeHeaderName(name);
|
|
133
|
-
const allowed = new Set((policy.allowed ?? []).map(normalizeHeaderName));
|
|
134
|
-
if (allowed.has(key)) return true;
|
|
135
|
-
if (key.startsWith("x-middleware-")) return false;
|
|
136
|
-
const blocked = /* @__PURE__ */ new Set([
|
|
137
|
-
...DEFAULT_BLOCKED_REQUEST_HEADERS.map(normalizeHeaderName),
|
|
138
|
-
...(policy.blocked ?? []).map(normalizeHeaderName)
|
|
139
|
-
]);
|
|
140
|
-
return !blocked.has(key);
|
|
141
|
-
}
|
|
142
|
-
function mergeRequestHeaderOverrides(target, overrides, policy = {}) {
|
|
143
|
-
const dropped = [];
|
|
144
|
-
let applied = 0;
|
|
145
|
-
overrides.forEach((value, key) => {
|
|
146
|
-
if (!isRequestHeaderAllowed(key, policy)) {
|
|
147
|
-
dropped.push(key);
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
target.set(key, value);
|
|
151
|
-
applied++;
|
|
152
|
-
});
|
|
153
|
-
return { applied, dropped };
|
|
154
|
-
}
|
|
155
93
|
function parseCookieName(setCookie) {
|
|
156
94
|
const eq = setCookie.indexOf("=");
|
|
157
95
|
return (eq === -1 ? setCookie : setCookie.slice(0, eq)).trim();
|
|
@@ -511,11 +449,10 @@ function hostGlobToRegex(value) {
|
|
|
511
449
|
}
|
|
512
450
|
function host(matcher) {
|
|
513
451
|
const list = Array.isArray(matcher) ? matcher : [matcher];
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
return
|
|
452
|
+
return list.map((m) => {
|
|
453
|
+
const source = m instanceof RegExp ? m.source : hostGlobToRegex(m);
|
|
454
|
+
return new RegExp(`^(?:${source})$`, "i");
|
|
517
455
|
});
|
|
518
|
-
return toStatelessRegExp(new RegExp(`^(?:${parts.join("|")})$`, "i"));
|
|
519
456
|
}
|
|
520
457
|
function isScopeObject(value) {
|
|
521
458
|
return "host" in value || "path" in value;
|
|
@@ -572,16 +509,14 @@ function path(pattern) {
|
|
|
572
509
|
if (pattern instanceof RegExp) return compileRegexPath(pattern);
|
|
573
510
|
return compileStringPath(pattern);
|
|
574
511
|
}
|
|
575
|
-
function
|
|
512
|
+
function toPathRegexes(matcher) {
|
|
576
513
|
const list = Array.isArray(matcher) ? matcher : [matcher];
|
|
577
|
-
|
|
578
|
-
if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
|
|
579
|
-
return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
|
|
514
|
+
return list.map((m) => toStatelessRegExp(path(m)));
|
|
580
515
|
}
|
|
581
516
|
function compileScopes(input) {
|
|
582
517
|
if (input == null) return void 0;
|
|
583
518
|
const list = Array.isArray(input) ? input : [input];
|
|
584
|
-
const compilePath = (matcher) =>
|
|
519
|
+
const compilePath = (matcher) => toPathRegexes(matcher);
|
|
585
520
|
const compiled = [];
|
|
586
521
|
for (const item of list) {
|
|
587
522
|
if (typeof item === "string" || item instanceof RegExp) {
|
|
@@ -604,10 +539,10 @@ function compileScopes(input) {
|
|
|
604
539
|
}
|
|
605
540
|
function scopeMatches(pathname, hostname, scope) {
|
|
606
541
|
if (scope.host) {
|
|
607
|
-
if (!hostname || !scope.host.test(hostname)) return false;
|
|
542
|
+
if (!hostname || !scope.host.some((alternative) => alternative.test(hostname))) return false;
|
|
608
543
|
}
|
|
609
544
|
if (scope.path) {
|
|
610
|
-
if (!scope.path.test(pathname)) return false;
|
|
545
|
+
if (!scope.path.some((alternative) => alternative.test(pathname))) return false;
|
|
611
546
|
}
|
|
612
547
|
return true;
|
|
613
548
|
}
|
|
@@ -622,12 +557,12 @@ function toRule(entry) {
|
|
|
622
557
|
const harden = (scopes) => scopes?.map((s) => {
|
|
623
558
|
if (!s.host && !s.path) {
|
|
624
559
|
throw new Error(
|
|
625
|
-
"[proxy-chain] include/exclude scope needs
|
|
560
|
+
"[proxy-chain] include/exclude scope needs a path, host, or host/path object."
|
|
626
561
|
);
|
|
627
562
|
}
|
|
628
563
|
return {
|
|
629
|
-
host: s.host
|
|
630
|
-
path: s.path
|
|
564
|
+
host: s.host?.map(toStatelessRegExp),
|
|
565
|
+
path: s.path?.map(toStatelessRegExp)
|
|
631
566
|
};
|
|
632
567
|
});
|
|
633
568
|
return {
|
|
@@ -641,23 +576,6 @@ function ruleLabel(rule, index) {
|
|
|
641
576
|
const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
|
|
642
577
|
return extractMeaningfulName(rule.name) ?? runName ?? `rule#${index}`;
|
|
643
578
|
}
|
|
644
|
-
function withPaths(entry, filter) {
|
|
645
|
-
const base = toRule(entry);
|
|
646
|
-
const include = compileScopes(filter.include);
|
|
647
|
-
const exclude = compileScopes(filter.exclude);
|
|
648
|
-
const name = filter.name ?? base.name;
|
|
649
|
-
assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
|
|
650
|
-
return {
|
|
651
|
-
run: base.run,
|
|
652
|
-
include,
|
|
653
|
-
exclude,
|
|
654
|
-
name,
|
|
655
|
-
debug: base.debug,
|
|
656
|
-
timeout: base.timeout,
|
|
657
|
-
when: base.when,
|
|
658
|
-
diagnosticRules: { include: filter.include, exclude: filter.exclude }
|
|
659
|
-
};
|
|
660
|
-
}
|
|
661
579
|
function ruleMatchReason(pathname, hostname, rule) {
|
|
662
580
|
if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) {
|
|
663
581
|
return "exclude-match";
|
|
@@ -688,7 +606,9 @@ function canonicalPathname(pathname) {
|
|
|
688
606
|
return decoded.length > 1 ? decoded.replace(/\/+$/, "") || "/" : decoded;
|
|
689
607
|
}
|
|
690
608
|
function scopeKey(scope) {
|
|
691
|
-
|
|
609
|
+
const path2 = scope.path?.map((alternative) => `${alternative.source}::${alternative.flags}`).join("&");
|
|
610
|
+
const hostKey = scope.host?.map((alternative) => `${alternative.source}::${alternative.flags}`).join("&");
|
|
611
|
+
return `${hostKey ?? "*"}|${path2 ?? "*"}`;
|
|
692
612
|
}
|
|
693
613
|
function assertIncludeExcludeNoOverlap(include, exclude, label) {
|
|
694
614
|
if (!include?.length || !exclude?.length) return;
|
|
@@ -750,45 +670,21 @@ function assertOverrideMechanismSupported(strict = false) {
|
|
|
750
670
|
return false;
|
|
751
671
|
}
|
|
752
672
|
}
|
|
753
|
-
function resolveRuleResult(res
|
|
754
|
-
if (res
|
|
673
|
+
function resolveRuleResult(res) {
|
|
674
|
+
if (res === void 0) {
|
|
755
675
|
return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
|
|
756
676
|
}
|
|
757
|
-
if (!
|
|
677
|
+
if (!(res instanceof Response)) {
|
|
758
678
|
throw new TypeError(
|
|
759
|
-
`[proxy-chain] rule must return
|
|
679
|
+
`[proxy-chain] rule must return a Response or undefined. Got ${typeof res}.`
|
|
760
680
|
);
|
|
761
681
|
}
|
|
762
|
-
if (isNextResult(res)) {
|
|
763
|
-
let request;
|
|
764
|
-
if (res.request) {
|
|
765
|
-
const filtered = new Headers();
|
|
766
|
-
const { dropped } = mergeRequestHeaderOverrides(
|
|
767
|
-
filtered,
|
|
768
|
-
headersInitToHeaders(res.request),
|
|
769
|
-
requestHeaderPolicy
|
|
770
|
-
);
|
|
771
|
-
if (debug && dropped.length) {
|
|
772
|
-
logger.warn({ dropped }, "blocked request header mutation");
|
|
773
|
-
}
|
|
774
|
-
if ([...filtered.keys()].length) request = filtered;
|
|
775
|
-
}
|
|
776
|
-
const headerInit = res.headers ? headersInitToHeaders(res.headers) : void 0;
|
|
777
|
-
return {
|
|
778
|
-
kind: "continue",
|
|
779
|
-
request,
|
|
780
|
-
responseHeaders: headerInit ? responseHeaderItems(headerInit) : /* @__PURE__ */ new Map(),
|
|
781
|
-
cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
|
|
782
|
-
};
|
|
783
|
-
}
|
|
784
682
|
if (res instanceof NextResponse && res.headers.get("x-middleware-next") === "1") {
|
|
785
683
|
let request;
|
|
786
684
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
787
685
|
const hasRequestOverride = res.headers.has("x-middleware-override-headers");
|
|
788
686
|
if (hasRequestOverride) {
|
|
789
|
-
|
|
790
|
-
mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
|
|
791
|
-
request = target;
|
|
687
|
+
request = decoded;
|
|
792
688
|
}
|
|
793
689
|
return {
|
|
794
690
|
kind: "continue",
|
|
@@ -804,9 +700,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
804
700
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
805
701
|
const hasRequestOverride = res.headers.has("x-middleware-override-headers");
|
|
806
702
|
if (hasRequestOverride) {
|
|
807
|
-
|
|
808
|
-
mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
|
|
809
|
-
request = target;
|
|
703
|
+
request = decoded;
|
|
810
704
|
}
|
|
811
705
|
return {
|
|
812
706
|
kind: "continue",
|
|
@@ -1015,8 +909,11 @@ function safeLogger(logger) {
|
|
|
1015
909
|
error: wrap("error")
|
|
1016
910
|
};
|
|
1017
911
|
}
|
|
1018
|
-
function
|
|
1019
|
-
return value instanceof
|
|
912
|
+
function isTerminalRecovery(value) {
|
|
913
|
+
return value instanceof Response && resolveRuleResult(value).kind === "stop";
|
|
914
|
+
}
|
|
915
|
+
function isContinuingRecovery(value) {
|
|
916
|
+
return value instanceof Response && resolveRuleResult(value).kind === "continue";
|
|
1020
917
|
}
|
|
1021
918
|
function stripRoutingOverrides(res) {
|
|
1022
919
|
const plain = !(res instanceof NextResponse2);
|
|
@@ -1043,7 +940,6 @@ function resolveConfig(overrides) {
|
|
|
1043
940
|
headerMergeStrategy: "last-write-wins",
|
|
1044
941
|
debug: false,
|
|
1045
942
|
timeout: 0,
|
|
1046
|
-
requestHeaderPolicy: {},
|
|
1047
943
|
strictOverrideCheck: false,
|
|
1048
944
|
tracePath: true,
|
|
1049
945
|
...rest,
|
|
@@ -1062,7 +958,6 @@ function executeChain(options, entries) {
|
|
|
1062
958
|
cookieMergeStrategy,
|
|
1063
959
|
headerMergeStrategy,
|
|
1064
960
|
timeout,
|
|
1065
|
-
requestHeaderPolicy,
|
|
1066
961
|
strictOverrideCheck
|
|
1067
962
|
} = config;
|
|
1068
963
|
const debug = debugLevel !== false;
|
|
@@ -1167,16 +1062,7 @@ function executeChain(options, entries) {
|
|
|
1167
1062
|
return currentReq;
|
|
1168
1063
|
}
|
|
1169
1064
|
const nextUrl = currentReq.nextUrl.clone();
|
|
1170
|
-
const merged = new Headers();
|
|
1171
|
-
if (replaceRequestHeaders) {
|
|
1172
|
-
currentReq.headers.forEach((value, key) => {
|
|
1173
|
-
if (!isRequestHeaderAllowed(key, requestHeaderPolicy)) merged.set(key, value);
|
|
1174
|
-
});
|
|
1175
|
-
} else {
|
|
1176
|
-
currentReq.headers.forEach((value, key) => {
|
|
1177
|
-
merged.set(key, value);
|
|
1178
|
-
});
|
|
1179
|
-
}
|
|
1065
|
+
const merged = replaceRequestHeaders ? new Headers() : new Headers(currentReq.headers);
|
|
1180
1066
|
pendingRequestOverrides.forEach((v, k) => {
|
|
1181
1067
|
merged.set(k, v);
|
|
1182
1068
|
});
|
|
@@ -1267,7 +1153,7 @@ function executeChain(options, entries) {
|
|
|
1267
1153
|
(signal) => errorHandler(err, i, req2, contextFor(signal))
|
|
1268
1154
|
);
|
|
1269
1155
|
if (timeoutError || requestCancelled) {
|
|
1270
|
-
if (
|
|
1156
|
+
if (isTerminalRecovery(recovered)) {
|
|
1271
1157
|
const response2 = stripRoutingOverrides(recovered);
|
|
1272
1158
|
headerWrites.push({
|
|
1273
1159
|
ruleIndex: i,
|
|
@@ -1322,17 +1208,8 @@ function executeChain(options, entries) {
|
|
|
1322
1208
|
if (recovered == null) {
|
|
1323
1209
|
return stopFailure(errorPolicy);
|
|
1324
1210
|
}
|
|
1325
|
-
if (
|
|
1326
|
-
|
|
1327
|
-
name: safeDiagnosticText(label, 64),
|
|
1328
|
-
outcome: "recovered",
|
|
1329
|
-
durationMs,
|
|
1330
|
-
recovery: "continue",
|
|
1331
|
-
policy: errorPolicy,
|
|
1332
|
-
details
|
|
1333
|
-
});
|
|
1334
|
-
nextHandlerIndex = i + 1;
|
|
1335
|
-
return { raw: recovered };
|
|
1211
|
+
if (isContinuingRecovery(recovered)) {
|
|
1212
|
+
return { raw: recovered, recovered: { durationMs, policy: errorPolicy, details } };
|
|
1336
1213
|
}
|
|
1337
1214
|
if (!(recovered instanceof Response)) {
|
|
1338
1215
|
diagnostics?.push({
|
|
@@ -1441,6 +1318,7 @@ function executeChain(options, entries) {
|
|
|
1441
1318
|
const effectiveTimeout = rule.timeout ?? timeout;
|
|
1442
1319
|
let phase = rule.when ? "when" : "handler";
|
|
1443
1320
|
let result;
|
|
1321
|
+
let recoveredRule;
|
|
1444
1322
|
try {
|
|
1445
1323
|
result = await runInExecutionScope(
|
|
1446
1324
|
req.signal,
|
|
@@ -1482,17 +1360,19 @@ function executeChain(options, entries) {
|
|
|
1482
1360
|
);
|
|
1483
1361
|
if ("response" in recovered) return recovered.response;
|
|
1484
1362
|
result = { kind: "result", raw: recovered.raw };
|
|
1363
|
+
recoveredRule = recovered.recovered;
|
|
1485
1364
|
}
|
|
1486
1365
|
let raw = result.raw;
|
|
1487
1366
|
let duration2 = monotonicNow() - executionStartedAt;
|
|
1488
1367
|
let outcome;
|
|
1489
1368
|
try {
|
|
1490
|
-
outcome = resolveRuleResult(raw
|
|
1369
|
+
outcome = resolveRuleResult(raw);
|
|
1491
1370
|
} catch (err) {
|
|
1492
1371
|
const recovered = await recoverRuleError(err, i, label, activeReq, duration2, "result");
|
|
1493
1372
|
if ("response" in recovered) return recovered.response;
|
|
1494
1373
|
raw = recovered.raw;
|
|
1495
|
-
|
|
1374
|
+
recoveredRule = recovered.recovered;
|
|
1375
|
+
outcome = resolveRuleResult(raw);
|
|
1496
1376
|
}
|
|
1497
1377
|
if (outcome.kind === "continue") {
|
|
1498
1378
|
if (outcome.rewriteUrl) {
|
|
@@ -1513,7 +1393,16 @@ function executeChain(options, entries) {
|
|
|
1513
1393
|
headerWrites.push({ ruleIndex: i, ruleName: label, items: outcome.responseHeaders });
|
|
1514
1394
|
cookieWrites.push({ ruleIndex: i, ruleName: label, items: outcome.cookies });
|
|
1515
1395
|
}
|
|
1516
|
-
if (
|
|
1396
|
+
if (recoveredRule) {
|
|
1397
|
+
diagnostics?.push({
|
|
1398
|
+
name: safeDiagnosticText(label, 64),
|
|
1399
|
+
outcome: "recovered",
|
|
1400
|
+
durationMs: recoveredRule.durationMs,
|
|
1401
|
+
recovery: outcome.rewriteUrl ? "rewrite" : "continue",
|
|
1402
|
+
policy: recoveredRule.policy,
|
|
1403
|
+
details: recoveredRule.details
|
|
1404
|
+
});
|
|
1405
|
+
} else {
|
|
1517
1406
|
diagnostics?.push(
|
|
1518
1407
|
outcome.rewriteUrl ? {
|
|
1519
1408
|
name: safeDiagnosticText(label, 64),
|
|
@@ -1525,7 +1414,7 @@ function executeChain(options, entries) {
|
|
|
1525
1414
|
} : {
|
|
1526
1415
|
name: safeDiagnosticText(label, 64),
|
|
1527
1416
|
outcome: "continue",
|
|
1528
|
-
source:
|
|
1417
|
+
source: raw instanceof NextResponse2 && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
|
|
1529
1418
|
durationMs: duration2,
|
|
1530
1419
|
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1531
1420
|
}
|
|
@@ -1624,7 +1513,7 @@ function executeChain(options, entries) {
|
|
|
1624
1513
|
req.signal,
|
|
1625
1514
|
(signal) => config.onError(err, -1, materializeRequest(), contextFor(signal))
|
|
1626
1515
|
);
|
|
1627
|
-
if (
|
|
1516
|
+
if (isTerminalRecovery(recovered)) {
|
|
1628
1517
|
const response = stripRoutingOverrides(recovered);
|
|
1629
1518
|
return finish(
|
|
1630
1519
|
finalizeResponse(
|
|
@@ -1649,47 +1538,28 @@ function executeChain(options, entries) {
|
|
|
1649
1538
|
};
|
|
1650
1539
|
}
|
|
1651
1540
|
|
|
1652
|
-
// src/core/chain.ts
|
|
1653
|
-
function isDefinedHandler(value) {
|
|
1654
|
-
return typeof value === "object" && value !== null && value[DEFINED_HANDLER] === true;
|
|
1655
|
-
}
|
|
1656
|
-
function isScopeObject2(value) {
|
|
1657
|
-
return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
|
|
1658
|
-
}
|
|
1659
|
-
function toFilter(scope) {
|
|
1660
|
-
if (isScopeObject2(scope)) return { include: scope.include, exclude: scope.exclude };
|
|
1661
|
-
return { include: scope };
|
|
1662
|
-
}
|
|
1663
|
-
function fromNative(handler) {
|
|
1664
|
-
const run = (req, ctx, event) => handler(req, event, ctx);
|
|
1665
|
-
const name = handler.name && handler.name !== "proxy" ? handler.name : void 0;
|
|
1666
|
-
return { run, name };
|
|
1667
|
-
}
|
|
1668
|
-
function toEntry(entry) {
|
|
1669
|
-
if (Array.isArray(entry)) {
|
|
1670
|
-
const [target, scope] = entry;
|
|
1671
|
-
const filter = toFilter(scope);
|
|
1672
|
-
if (isDefinedHandler(target)) return withPaths(target, filter);
|
|
1673
|
-
return withPaths(fromNative(target), filter);
|
|
1674
|
-
}
|
|
1675
|
-
if (isDefinedHandler(entry)) return entry;
|
|
1676
|
-
if (typeof entry === "function") return fromNative(entry);
|
|
1677
|
-
throw new TypeError(
|
|
1678
|
-
"[proxy-chain] chain entries must be native handlers or defineHandler() results"
|
|
1679
|
-
);
|
|
1680
|
-
}
|
|
1681
|
-
function chain(entries, options) {
|
|
1682
|
-
const normalized = entries.map((entry) => toEntry(entry));
|
|
1683
|
-
return executeChain(options ?? {}, normalized);
|
|
1684
|
-
}
|
|
1685
|
-
|
|
1686
1541
|
// src/core/handler.ts
|
|
1687
|
-
function
|
|
1542
|
+
function assertHandlerConfig(options) {
|
|
1543
|
+
if (!options || typeof options !== "object" || typeof options.name !== "string" || options.name.trim() === "" || typeof options.handle !== "function") {
|
|
1544
|
+
throw new TypeError("[proxy-chain] configured handlers require a non-empty name and handle");
|
|
1545
|
+
}
|
|
1546
|
+
if ("handler" in options) {
|
|
1547
|
+
throw new TypeError(
|
|
1548
|
+
"[proxy-chain] configured handler property 'handler' is unsupported; use 'handle'"
|
|
1549
|
+
);
|
|
1550
|
+
}
|
|
1551
|
+
if ("config" in options || "options" in options) {
|
|
1552
|
+
throw new TypeError("[proxy-chain] handler configuration must use top-level options");
|
|
1553
|
+
}
|
|
1688
1554
|
assertValidTimeout(options.timeout);
|
|
1555
|
+
}
|
|
1556
|
+
function toHandlerRule(options) {
|
|
1557
|
+
assertHandlerConfig(options);
|
|
1558
|
+
const { handle } = options;
|
|
1689
1559
|
const include = compileScopes(options.rules?.include);
|
|
1690
1560
|
const exclude = compileScopes(options.rules?.exclude);
|
|
1691
|
-
|
|
1692
|
-
run: (request, context, event) =>
|
|
1561
|
+
return {
|
|
1562
|
+
run: (request, context, event) => handle(request, event, context),
|
|
1693
1563
|
name: options.name,
|
|
1694
1564
|
include,
|
|
1695
1565
|
exclude,
|
|
@@ -1702,14 +1572,31 @@ function defineHandler(options) {
|
|
|
1702
1572
|
exclude: options.rules?.exclude
|
|
1703
1573
|
}
|
|
1704
1574
|
};
|
|
1705
|
-
|
|
1575
|
+
}
|
|
1576
|
+
function defineHandler(options) {
|
|
1577
|
+
assertHandlerConfig(options);
|
|
1578
|
+
return options;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
// src/core/chain.ts
|
|
1582
|
+
function fromNative(handle) {
|
|
1583
|
+
const run = (req, ctx, event) => handle(req, event, ctx);
|
|
1584
|
+
const name = handle.name && handle.name !== "proxy" ? handle.name : void 0;
|
|
1585
|
+
return { run, name };
|
|
1586
|
+
}
|
|
1587
|
+
function toEntry(entry) {
|
|
1588
|
+
if (typeof entry === "function") return fromNative(entry);
|
|
1589
|
+
if (Array.isArray(entry)) {
|
|
1590
|
+
throw new TypeError("[proxy-chain] tuple entries are not supported; use a configured handler");
|
|
1591
|
+
}
|
|
1592
|
+
if (entry && typeof entry === "object") return toHandlerRule(entry);
|
|
1593
|
+
throw new TypeError("[proxy-chain] chain entries must be native handlers or configured handlers");
|
|
1594
|
+
}
|
|
1595
|
+
function chain(entries, options) {
|
|
1596
|
+
const normalized = entries.map((entry) => toEntry(entry));
|
|
1597
|
+
return executeChain(options ?? {}, normalized);
|
|
1706
1598
|
}
|
|
1707
1599
|
export {
|
|
1708
|
-
RuleTimeoutError,
|
|
1709
1600
|
chain,
|
|
1710
|
-
defineHandler
|
|
1711
|
-
host,
|
|
1712
|
-
isNextResult,
|
|
1713
|
-
next,
|
|
1714
|
-
path
|
|
1601
|
+
defineHandler
|
|
1715
1602
|
};
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# API reference
|
|
2
|
+
|
|
3
|
+
The runtime entry exports two functions:
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { chain, defineHandler } from "@klnap/next-proxy-chain";
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Next.js owns HTTP responses. Use `NextResponse` from `next/server` and standard Web `Response`, `Headers`, and `AbortSignal`.
|
|
10
|
+
|
|
11
|
+
## `chain()`
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
chain<TContext extends object = object>(
|
|
15
|
+
entries: readonly ChainEntry<TContext>[],
|
|
16
|
+
options?: ChainOptions<TContext>,
|
|
17
|
+
): (request: NextRequest, event: NextFetchEvent) => Promise<NextResponse | Response>
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`chain()` accepts native handler functions and configured handler objects. Entries run sequentially. A `NextResponse.next()` or `undefined` continues; redirects and terminal responses stop.
|
|
21
|
+
|
|
22
|
+
## `defineHandler()`
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
defineHandler<TContext extends object = object>(
|
|
26
|
+
options: HandlerConfig<TContext>,
|
|
27
|
+
): HandlerConfig<TContext>
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
It validates and returns the same configuration object. Inline and reusable configurations have the same type and normalization behavior.
|
|
31
|
+
|
|
32
|
+
## Configured handler
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
type HandlerConfig<TContext extends object = object> = {
|
|
36
|
+
name: string;
|
|
37
|
+
rules?: {
|
|
38
|
+
include?: RouteScopeList;
|
|
39
|
+
exclude?: RouteScopeList;
|
|
40
|
+
when?: HandlerWhen<TContext>;
|
|
41
|
+
};
|
|
42
|
+
timeout?: number;
|
|
43
|
+
debug?: DebugLevel;
|
|
44
|
+
onError?: OnErrorHandler<TContext>;
|
|
45
|
+
handle: NativeProxy<TContext>;
|
|
46
|
+
};
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`name` must be a non-empty string. `handle` must be a function. `rules`, `timeout`, `debug`, and `onError` are optional. `handle` appears last in examples by convention, not requirement.
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
defineHandler({
|
|
53
|
+
name: "authentication",
|
|
54
|
+
rules: { include: "/dashboard/**" },
|
|
55
|
+
timeout: 500,
|
|
56
|
+
debug: true,
|
|
57
|
+
onError: handleError,
|
|
58
|
+
handle: async (request, event, context) => {
|
|
59
|
+
return authenticate(request, event, context.signal);
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Arrow functions are the primary convention for `handle`, `when`, and `onError`. Async functions, function references, and object method syntax also satisfy the contract.
|
|
65
|
+
|
|
66
|
+
## Native handler
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
type NativeProxy<TContext extends object = object> = (
|
|
70
|
+
request: NextRequest,
|
|
71
|
+
event: NextFetchEvent,
|
|
72
|
+
context: HandlerContext<TContext>,
|
|
73
|
+
) =>
|
|
74
|
+
| NextResponse
|
|
75
|
+
| Response
|
|
76
|
+
| undefined
|
|
77
|
+
| void
|
|
78
|
+
| Promise<NextResponse | Response | undefined | void>;
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Two-argument Next.js handlers remain composable. The chain adds context as the optional third callback argument and passes through the original `event`.
|
|
82
|
+
|
|
83
|
+
## Matching
|
|
84
|
+
|
|
85
|
+
`Next.js config.matcher` filters whether the entrypoint runs. Handler `rules` filter configured handlers after entrypoint invocation.
|
|
86
|
+
|
|
87
|
+
- `include` and `exclude` accept a path string, `RegExp`, or objects with `path` and/or `host`.
|
|
88
|
+
- `*` matches one path segment. `**` matches zero or more segments.
|
|
89
|
+
- `exclude` takes precedence over `include`.
|
|
90
|
+
- `when(request, event, context)` may return a boolean or `Promise<boolean>`.
|
|
91
|
+
- Matching uses the effective request at each handler's turn. A continued rewrite changes later path matching and the query visible to predicates; original context metadata remains unchanged.
|
|
92
|
+
- Rewrites do not change the host used for matching. Host scopes read the effective `host` header, falling back to `x-forwarded-host`; a prior native request-header replacement of either header changes later host matching.
|
|
93
|
+
|
|
94
|
+
Host matcher strings compare case-insensitively and ignore ports. Host wildcards match one DNS label. See [Concepts](concepts.md#matching) for examples.
|
|
95
|
+
|
|
96
|
+
## Return values
|
|
97
|
+
|
|
98
|
+
| Handler returns | Chain behavior |
|
|
99
|
+
| ---------------------------- | ------------------------------------------------- |
|
|
100
|
+
| `undefined` | Continue to the next handler. |
|
|
101
|
+
| `NextResponse.next()` | Compose HTTP effects and continue. |
|
|
102
|
+
| `NextResponse.rewrite(url)` | Stage the rewrite and continue to later handlers. |
|
|
103
|
+
| `NextResponse.redirect(url)` | Stop and redirect. |
|
|
104
|
+
| Terminal `Response` | Stop and return the response. |
|
|
105
|
+
|
|
106
|
+
Only `NextResponse` routing responses are interpreted as continuation or rewrite instructions. A plain `Response` remains terminal, even if it contains Next.js routing headers.
|
|
107
|
+
|
|
108
|
+
`NextResponse.rewrite()` continues only for a successful rewrite response. Non-success responses are terminal. Redirects are terminal.
|
|
109
|
+
|
|
110
|
+
## Request headers
|
|
111
|
+
|
|
112
|
+
Use native `NextResponse.next({ request: { headers } })`. Next.js treats `headers` as the replacement request-header set, not a partial merge. Clone the effective request headers to preserve them:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
const headers = new Headers(request.headers);
|
|
116
|
+
headers.set("x-request-id", context.requestId);
|
|
117
|
+
return NextResponse.next({ request: { headers } });
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Removing a header means deleting it from the `Headers` instance before returning it. A replacement that omits a prior request header deletes that header downstream.
|
|
121
|
+
|
|
122
|
+
Each continued native override becomes the effective request seen by later rules. The engine reconstructs `NextRequest` using Next.js's encoded override metadata, while retaining staged rewrite URL state, request signal, and original chain metadata. Request headers remain separate from client-facing response headers.
|
|
123
|
+
|
|
124
|
+
There is no package-level request-header allow/deny policy. Handler code explicitly chooses the forwarded header set. Validate untrusted values before adding or changing headers.
|
|
125
|
+
|
|
126
|
+
## Response headers and cookies
|
|
127
|
+
|
|
128
|
+
Mutate the native response:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
const response = NextResponse.next();
|
|
132
|
+
response.headers.set("x-content-type-options", "nosniff");
|
|
133
|
+
response.cookies.set("locale", "en");
|
|
134
|
+
return response;
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Continued response headers and cookies compose onto the final response. The default merge strategy is last-write-wins. `headerMergeStrategy` and `cookieMergeStrategy` can select `"first-write-wins"` or a custom resolver; returning `null` from a resolver removes that header or cookie identity.
|
|
138
|
+
|
|
139
|
+
Cookie identity includes cookie name, domain, and path. Distinct paths remain distinct.
|
|
140
|
+
|
|
141
|
+
## Context and cancellation
|
|
142
|
+
|
|
143
|
+
`HandlerContext<TContext>` contains:
|
|
144
|
+
|
|
145
|
+
- `requestId`: generated `req_` identifier.
|
|
146
|
+
- `startedAt`: request start time.
|
|
147
|
+
- `elapsedMs`: elapsed request duration.
|
|
148
|
+
- `originalUrl`, `originalPathname`, and `originalHostname`: original request metadata.
|
|
149
|
+
- `signal`: execution-scoped `AbortSignal`.
|
|
150
|
+
- Custom properties from `TContext`.
|
|
151
|
+
|
|
152
|
+
Custom state is shared between handlers for one request and isolated across requests. Properties may be `undefined` until initialized. Context and request IDs are not forwarded to route handlers automatically.
|
|
153
|
+
|
|
154
|
+
## Errors and timeouts
|
|
155
|
+
|
|
156
|
+
`timeout` is a per-handler execution budget in milliseconds; `0` disables timeouts. A handler's timeout overrides the chain timeout. The handler's predicate shares its budget. Timeout aborts the execution signal and stops the chain.
|
|
157
|
+
|
|
158
|
+
Handler-level `onError` takes precedence over chain-level `onError`. For ordinary errors, returning `NextResponse.next()` or a successful `NextResponse.rewrite()` continues after the failed handler; a rewrite is staged like a normal rewrite. Returning any other `Response` terminates with that response. Returning `undefined`, `void`, or `null`, throwing, or returning an unsupported value fails closed.
|
|
159
|
+
|
|
160
|
+
For timeout, request cancellation, and engine-level failures, recovery accepts only a terminal Web `Response`, including a redirect. `NextResponse.next()` and successful `NextResponse.rewrite()` are rejected because they would resume routing. A rejected timeout or engine-level recovery returns `500`. Without recovery, timeout returns `500`. Cancellation stops the package chain and returns a native `NextResponse.next()` handoff; Next.js may continue downstream routing, so this is not a fail-closed response. Error diagnostics record the chosen recovery policy.
|
|
161
|
+
|
|
162
|
+
## Chain options
|
|
163
|
+
|
|
164
|
+
| Option | Default | Meaning |
|
|
165
|
+
| --------------------- | ------------------- | --------------------------------------------------------------------------------------------------- |
|
|
166
|
+
| `timeout` | `0` | Per-handler deadline in milliseconds. |
|
|
167
|
+
| `debug` | `false` | Disable logs, or select `true`, `"compact"`, `"detailed"`, or `"verbose"`. |
|
|
168
|
+
| `logger` | Console logger | Logger with `debug`, `info`, `warn`, and `error` methods. |
|
|
169
|
+
| `onError` | None | Chain-level error recovery. Handler-level `onError` takes precedence. |
|
|
170
|
+
| `onTrace` | None | Receives structured request traces. |
|
|
171
|
+
| `tracePath` | `true` | Include the original request pathname in the top-level structured trace and formatted request line. |
|
|
172
|
+
| `headerMergeStrategy` | `"last-write-wins"` | Resolve response-header conflicts. |
|
|
173
|
+
| `cookieMergeStrategy` | `"last-write-wins"` | Resolve cookie conflicts. |
|
|
174
|
+
| `strictOverrideCheck` | `false` | Throw at chain creation if native Next.js request-header override metadata cannot be verified. |
|
|
175
|
+
|
|
176
|
+
Handler `timeout` and `debug` override their chain-level values. Chain-level `onError` is used only when a handler does not define its own.
|
|
177
|
+
|
|
178
|
+
`strictOverrideCheck` tests whether the active Next.js `NextResponse.next()` encodes a sentinel request-header override. The probe runs when the first chain is constructed and caches its result for that package module. A successful probe is silent and leaves normal native header replacement behavior unchanged.
|
|
179
|
+
|
|
180
|
+
If the probe reports unsupported behavior or throws, `strictOverrideCheck: true` throws during chain construction. With the default `false`, an uncached failed probe warns and chain construction continues; later chains reuse the result without probing again. The package does not emulate the override mechanism. Request-header replacements may then be missing from later handlers or downstream Next.js code. Use `true` to fail fast when the application depends on native request-header forwarding.
|
|
181
|
+
|
|
182
|
+
The probe checks Next.js's generated override metadata. It does not verify that the deployed runtime later applies that metadata.
|
|
183
|
+
|
|
184
|
+
`tracePath: false` removes only the original request pathname from `ChainTrace.pathname` and the formatted request line. It does not remove paths in matched scope details or rewrite and redirect destinations. Destination query values are replaced with `?[query]`.
|
|
185
|
+
|
|
186
|
+
## Public types
|
|
187
|
+
|
|
188
|
+
The package exports `ChainEntry`, `ChainOptions`, `HandlerConfig`, `NativeProxy`, `OnErrorHandler`, `OnErrorResult`, `HandlerContext`, `RequestMetadata`, matcher types, and structured diagnostic types.
|
|
189
|
+
|
|
190
|
+
It exports no helper-specific continuation token, response wrapper, or request-header policy.
|