akanjs 3.1.0 → 3.1.1-rc.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/base/primitiveRegistry.ts +3 -0
- package/client/cookie.ts +80 -35
- package/client/dictionaryAsset.ts +32 -0
- package/client/index.ts +1 -0
- package/client/makePageProto.tsx +9 -15
- package/client/native.ts +1 -22
- package/client/nativeHost.ts +22 -0
- package/client/route/LayoutDefinition.ts +3 -2
- package/client/route/RouteDefinition.ts +10 -5
- package/client/translator.ts +20 -60
- package/client/translatorState.ts +44 -0
- package/client/types.ts +1 -0
- package/common/IpLiteral.ts +75 -0
- package/common/TrustedProxy.ts +100 -71
- package/common/appHosts.ts +32 -0
- package/common/authCookie.ts +8 -5
- package/common/authToken.ts +24 -6
- package/common/clientAddress.ts +22 -11
- package/common/cookieJar.ts +90 -0
- package/common/cookieSweep.ts +77 -0
- package/common/index.ts +14 -1
- package/common/remoteAuthCode.ts +55 -0
- package/common/requestLocale.ts +28 -0
- package/common/sessionCookies.ts +43 -0
- package/common/types.ts +5 -0
- package/constant/constantRegistry.ts +33 -6
- package/constant/refNameClaims.ts +99 -0
- package/dictionary/base.dictionary.ts +5 -0
- package/document/databaseRegistry.ts +2 -2
- package/document/filterMeta.ts +2 -2
- package/fetch/client/fetchClient.ts +69 -25
- package/fetch/client/wsClient.ts +21 -4
- package/fetch/index.ts +1 -0
- package/fetch/renderScope.ts +54 -0
- package/fetch/requestStorage.ts +19 -9
- package/native/api.ts +1 -0
- package/native/config.ts +1 -0
- package/package.json +11 -1
- package/server/akanApp.ts +12 -11
- package/server/akanAppHeaders.ts +16 -14
- package/server/akanServer.ts +26 -4
- package/server/cachePolicy.ts +5 -3
- package/server/contentEncoding.ts +164 -26
- package/server/di/diLifecycle.ts +2 -0
- package/server/hmr/devArtifactPruner.ts +13 -3
- package/server/hmr/devHmrController.ts +1 -0
- package/server/imageOptimizer.ts +3 -1
- package/server/lifecycle/runtimeDir.ts +16 -1
- package/server/mcp/McpRouter.ts +54 -0
- package/server/ops/statusAccess.ts +59 -0
- package/server/routeState.ts +1 -0
- package/server/routing/apiRouter.ts +88 -4
- package/server/routing/appWsData.ts +11 -6
- package/server/routing/routeHosts.ts +31 -0
- package/server/routing/soloAppRoutes.ts +7 -4
- package/server/rscClient.tsx +31 -16
- package/server/rscPagePrompts.ts +7 -3
- package/server/rscWorker.tsx +3 -1
- package/server/ssrFromRscRenderer.tsx +11 -9
- package/server/ssrTypes.ts +2 -0
- package/server/types.tsx +7 -0
- package/server/vendor/tailwind-merge.ts +1 -0
- package/server/webRouter.ts +82 -22
- package/service/serve.ts +6 -3
- package/signal/endpointIdempotency.ts +3 -3
- package/signal/mcp/McpDocument.ts +25 -5
- package/signal/serializer/fetch.serializer.ts +1 -1
- package/signal/signalContext.ts +22 -10
- package/signal/slice.ts +19 -8
- package/store/storeInstance.ts +6 -5
- package/test/ServedMcpCatalogue.ts +44 -0
- package/test/index.ts +9 -1
- package/test/signalTestRuntime.ts +11 -1
- package/test/testServer.ts +21 -0
- package/types/base/primitiveRegistry.d.ts +1 -0
- package/types/client/cookie.d.ts +7 -7
- package/types/client/dictionaryAsset.d.ts +4 -0
- package/types/client/index.d.ts +1 -0
- package/types/client/native.d.ts +1 -8
- package/types/client/nativeHost.d.ts +8 -0
- package/types/client/translator.d.ts +4 -9
- package/types/client/translatorState.d.ts +21 -0
- package/types/client/types.d.ts +1 -0
- package/types/common/IpLiteral.d.ts +6 -0
- package/types/common/TrustedProxy.d.ts +6 -0
- package/types/common/appHosts.d.ts +7 -0
- package/types/common/authCookie.d.ts +3 -2
- package/types/common/authToken.d.ts +13 -0
- package/types/common/clientAddress.d.ts +6 -2
- package/types/common/cookieJar.d.ts +22 -0
- package/types/common/cookieSweep.d.ts +12 -0
- package/types/common/index.d.ts +7 -1
- package/types/common/remoteAuthCode.d.ts +9 -0
- package/types/common/requestLocale.d.ts +13 -0
- package/types/common/sessionCookies.d.ts +13 -0
- package/types/common/types.d.ts +5 -0
- package/types/constant/constantRegistry.d.ts +2 -1
- package/types/constant/refNameClaims.d.ts +12 -0
- package/types/dictionary/base.dictionary.d.ts +1 -1
- package/types/dictionary/dictionary.d.ts +8 -8
- package/types/document/filterMeta.d.ts +2 -2
- package/types/fetch/agentTurn.d.ts +1 -1
- package/types/fetch/client/fetchClient.d.ts +1 -0
- package/types/fetch/client/wsClient.d.ts +2 -0
- package/types/fetch/index.d.ts +1 -0
- package/types/fetch/renderScope.d.ts +18 -0
- package/types/fetch/requestStorage.d.ts +10 -5
- package/types/native/api.d.ts +1 -0
- package/types/native/config.d.ts +1 -0
- package/types/server/akanServer.d.ts +10 -1
- package/types/server/cachePolicy.d.ts +1 -1
- package/types/server/contentEncoding.d.ts +16 -4
- package/types/server/hmr/devArtifactPruner.d.ts +1 -0
- package/types/server/mcp/McpRouter.d.ts +16 -1
- package/types/server/ops/statusAccess.d.ts +15 -0
- package/types/server/routeState.d.ts +1 -0
- package/types/server/routing/appWsData.d.ts +4 -0
- package/types/server/routing/routeHosts.d.ts +4 -0
- package/types/server/routing/soloAppRoutes.d.ts +2 -1
- package/types/server/rscClient.d.ts +1 -0
- package/types/server/ssrTypes.d.ts +2 -0
- package/types/server/types.d.ts +6 -0
- package/types/server/vendor/tailwind-merge.d.ts +1 -0
- package/types/signal/mcp/McpDocument.d.ts +8 -0
- package/types/signal/signalContext.d.ts +6 -4
- package/types/signal/slice.d.ts +2 -1
- package/types/test/ServedMcpCatalogue.d.ts +15 -0
- package/types/test/index.d.ts +3 -2
- package/types/test/signalTestRuntime.d.ts +8 -1
- package/types/test/testServer.d.ts +15 -0
- package/types/ui/System/Client.d.ts +7 -5
- package/types/ui/System/Common.d.ts +1 -4
- package/types/ui/System/SSR.d.ts +2 -2
- package/types/ui/index.d.ts +2 -0
- package/types/ui/recipe/badgeRecipe.d.ts +2 -2
- package/types/ui/recipe/buttonRecipe.d.ts +2 -2
- package/types/ui/recipe/factory.d.ts +2 -1
- package/types/ui/recipe/inputRecipe.d.ts +2 -2
- package/ui/Clipboard.tsx +3 -1
- package/ui/Link/Anchor.tsx +1 -2
- package/ui/System/CSR.tsx +4 -2
- package/ui/System/Client.tsx +25 -17
- package/ui/System/Common.tsx +1 -5
- package/ui/System/SSR.tsx +4 -5
- package/ui/fontCss.ts +1 -1
- package/ui/index.ts +2 -0
- package/ui/recipe/factory.ts +17 -4
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export class IpLiteral {
|
|
2
|
+
|
|
3
|
+
static normalize(address: string): string {
|
|
4
|
+
const trimmed = address.trim();
|
|
5
|
+
const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(trimmed);
|
|
6
|
+
return mapped?.[1] ?? trimmed;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
static parse(entry: string): string | null {
|
|
10
|
+
const trimmed = entry.trim();
|
|
11
|
+
const bracketed = /^\[([^\]]*:[^\]]*)\](?::\d{1,5})?$/.exec(trimmed);
|
|
12
|
+
const v4WithPort = /^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(trimmed);
|
|
13
|
+
const [address = "", zone, ...rest] = (bracketed?.[1] ?? v4WithPort?.[1] ?? trimmed).split("%");
|
|
14
|
+
if (rest.length) return null;
|
|
15
|
+
if (zone !== undefined && !(address.includes(":") && /^[A-Za-z0-9_.-]{1,64}$/.test(zone))) return null;
|
|
16
|
+
const bytes = IpLiteral.bytes(IpLiteral.normalize(address));
|
|
17
|
+
|
|
18
|
+
return bytes ? IpLiteral.#format(bytes) : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
static bytes(address: string): Uint8Array | null {
|
|
22
|
+
if (address.includes(".") && !address.includes(":")) {
|
|
23
|
+
const parts = address.split(".");
|
|
24
|
+
if (parts.length !== 4) return null;
|
|
25
|
+
const bytes = new Uint8Array(4);
|
|
26
|
+
for (const [idx, part] of parts.entries()) {
|
|
27
|
+
const value = Number(part);
|
|
28
|
+
|
|
29
|
+
if (!/^(?:0|[1-9]\d{0,2})$/.test(part) || value > 255) return null;
|
|
30
|
+
bytes[idx] = value;
|
|
31
|
+
}
|
|
32
|
+
return bytes;
|
|
33
|
+
}
|
|
34
|
+
return address.includes(":") ? IpLiteral.#ipv6Bytes(address) : null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
static #ipv6Bytes(address: string): Uint8Array | null {
|
|
38
|
+
|
|
39
|
+
const bare = address.split("%")[0] ?? "";
|
|
40
|
+
const halves = bare.split("::");
|
|
41
|
+
if (halves.length > 2) return null;
|
|
42
|
+
const groupsOf = (text: string) => (text ? text.split(":").filter((group) => group !== "") : []);
|
|
43
|
+
const head = groupsOf(halves[0] ?? "");
|
|
44
|
+
const tail = halves.length === 2 ? groupsOf(halves[1] ?? "") : [];
|
|
45
|
+
const filled = halves.length === 2 ? 8 - head.length - tail.length : 0;
|
|
46
|
+
if (filled < 0 || head.length + tail.length + filled !== 8) return null;
|
|
47
|
+
const groups = [...head, ...new Array(filled).fill("0"), ...tail];
|
|
48
|
+
const bytes = new Uint8Array(16);
|
|
49
|
+
for (const [idx, group] of groups.entries()) {
|
|
50
|
+
if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
|
|
51
|
+
const value = Number.parseInt(group, 16);
|
|
52
|
+
bytes[idx * 2] = value >> 8;
|
|
53
|
+
bytes[idx * 2 + 1] = value & 0xff;
|
|
54
|
+
}
|
|
55
|
+
return bytes;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
static #format(bytes: Uint8Array): string {
|
|
59
|
+
if (bytes.length === 4) return bytes.join(".");
|
|
60
|
+
if (bytes.subarray(0, 10).every((byte) => byte === 0) && bytes[10] === 0xff && bytes[11] === 0xff)
|
|
61
|
+
return bytes.subarray(12).join(".");
|
|
62
|
+
const groups = Array.from({ length: 8 }, (_, idx) => ((bytes[idx * 2] ?? 0) << 8) | (bytes[idx * 2 + 1] ?? 0));
|
|
63
|
+
let runStart = -1;
|
|
64
|
+
let runLength = 1;
|
|
65
|
+
for (let start = 0; start < groups.length; ) {
|
|
66
|
+
let end = start;
|
|
67
|
+
while (end < groups.length && groups[end] === 0) end += 1;
|
|
68
|
+
if (end - start > runLength) [runStart, runLength] = [start, end - start];
|
|
69
|
+
start = Math.max(end, start + 1);
|
|
70
|
+
}
|
|
71
|
+
const hex = groups.map((group) => group.toString(16));
|
|
72
|
+
if (runStart < 0) return hex.join(":");
|
|
73
|
+
return `${hex.slice(0, runStart).join(":")}::${hex.slice(runStart + runLength).join(":")}`;
|
|
74
|
+
}
|
|
75
|
+
}
|
package/common/TrustedProxy.ts
CHANGED
|
@@ -1,39 +1,80 @@
|
|
|
1
1
|
import { clientAddressFromHeaders, normalizeIpAddress } from "./clientAddress";
|
|
2
|
+
import { IpLiteral } from "./IpLiteral";
|
|
3
|
+
import { Logger } from "./Logger";
|
|
4
|
+
|
|
5
|
+
interface Cidr {
|
|
6
|
+
bytes: Uint8Array;
|
|
7
|
+
bits: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface TrustPolicy {
|
|
11
|
+
trustAll: boolean;
|
|
12
|
+
privateRanges: boolean;
|
|
13
|
+
strict: boolean;
|
|
14
|
+
cidrs: Cidr[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ResolvedClient {
|
|
18
|
+
address: string | null;
|
|
19
|
+
/** Read from a trusted hop's forwarded headers rather than taken from the socket peer. */
|
|
20
|
+
forwarded: boolean;
|
|
21
|
+
}
|
|
2
22
|
|
|
3
23
|
export class TrustedProxy {
|
|
4
|
-
static #
|
|
5
|
-
static #trustAll: boolean | null = null;
|
|
24
|
+
static #policy: TrustPolicy | null = null;
|
|
6
25
|
|
|
7
26
|
static readonly #verdicts = new Map<string, boolean>();
|
|
8
27
|
static readonly #verdictLimit = 1024;
|
|
28
|
+
static #warnedIgnoredPeer = false;
|
|
9
29
|
|
|
10
30
|
static configure(list: string | null | undefined) {
|
|
31
|
+
TrustedProxy.reset();
|
|
32
|
+
TrustedProxy.#policy = TrustedProxy.#policyOf(list);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
static reset() {
|
|
36
|
+
TrustedProxy.#policy = null;
|
|
11
37
|
TrustedProxy.#verdicts.clear();
|
|
12
|
-
TrustedProxy.#
|
|
13
|
-
|
|
38
|
+
TrustedProxy.#warnedIgnoredPeer = false;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
static #load(): TrustPolicy {
|
|
42
|
+
TrustedProxy.#policy ??= TrustedProxy.#policyOf(process.env.AKAN_TRUSTED_PROXIES);
|
|
43
|
+
return TrustedProxy.#policy;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
static #policyOf(list: string | null | undefined): TrustPolicy {
|
|
47
|
+
const entries = (list ?? "")
|
|
14
48
|
.split(",")
|
|
15
49
|
.map((entry) => entry.trim())
|
|
16
|
-
.filter((entry) => entry
|
|
50
|
+
.filter((entry) => entry);
|
|
51
|
+
const keywords = new Set(entries.map((entry) => entry.toLowerCase()));
|
|
52
|
+
const cidrs = entries
|
|
53
|
+
.filter((entry) => !["*", "none", "private"].includes(entry.toLowerCase()))
|
|
17
54
|
.flatMap((entry) => {
|
|
18
55
|
const parsed = TrustedProxy.#parseCidr(entry);
|
|
56
|
+
if (!parsed)
|
|
57
|
+
new Logger("TrustedProxy").warn(
|
|
58
|
+
`AKAN_TRUSTED_PROXIES entry "${entry}" is neither an address nor a CIDR; ignored`,
|
|
59
|
+
);
|
|
19
60
|
return parsed ? [parsed] : [];
|
|
20
61
|
});
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
62
|
+
const trustAll = keywords.has("*");
|
|
63
|
+
if (trustAll && entries.length > 1)
|
|
64
|
+
new Logger("TrustedProxy").warn(
|
|
65
|
+
`AKAN_TRUSTED_PROXIES lists "*", which trusts every peer, so its other entries change nothing`,
|
|
66
|
+
);
|
|
67
|
+
return {
|
|
68
|
+
trustAll,
|
|
69
|
+
privateRanges: !entries.length || keywords.has("private"),
|
|
70
|
+
strict: entries.length > 0 && !trustAll,
|
|
71
|
+
cidrs,
|
|
72
|
+
};
|
|
31
73
|
}
|
|
32
74
|
|
|
33
75
|
static isTrusted(address: string | null | undefined): boolean {
|
|
34
76
|
if (!address) return false;
|
|
35
|
-
TrustedProxy.#load();
|
|
36
|
-
if (TrustedProxy.#trustAll) return true;
|
|
77
|
+
if (TrustedProxy.#load().trustAll) return true;
|
|
37
78
|
const known = TrustedProxy.#verdicts.get(address);
|
|
38
79
|
if (known !== undefined) return known;
|
|
39
80
|
const verdict = TrustedProxy.#judge(address);
|
|
@@ -43,26 +84,45 @@ export class TrustedProxy {
|
|
|
43
84
|
}
|
|
44
85
|
|
|
45
86
|
static #judge(address: string): boolean {
|
|
46
|
-
const bytes =
|
|
87
|
+
const bytes = IpLiteral.bytes(normalizeIpAddress(address));
|
|
47
88
|
if (!bytes) return false;
|
|
48
|
-
|
|
49
|
-
|
|
89
|
+
const policy = TrustedProxy.#load();
|
|
90
|
+
if (TrustedProxy.#isLoopback(bytes)) return true;
|
|
91
|
+
if (policy.privateRanges && TrustedProxy.#isPrivateRange(bytes)) return true;
|
|
92
|
+
return policy.cidrs.some((cidr) => TrustedProxy.#inRange(bytes, cidr));
|
|
50
93
|
}
|
|
51
94
|
|
|
52
95
|
/** A `null` peer is a unix socket, which only a local proxy opens, so its headers count; `undefined` is not. */
|
|
53
96
|
static clientAddress(headers: Headers, peerAddress: string | null | undefined): string | null {
|
|
97
|
+
return TrustedProxy.resolve(headers, peerAddress).address;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
static resolve(headers: Headers, peerAddress: string | null | undefined): ResolvedClient {
|
|
54
101
|
if (peerAddress === null || TrustedProxy.isTrusted(peerAddress)) {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
102
|
+
|
|
103
|
+
const judge = TrustedProxy.#load().strict ? (address: string) => TrustedProxy.isTrusted(address) : undefined;
|
|
104
|
+
const recorded = clientAddressFromHeaders(headers, judge);
|
|
105
|
+
if (recorded) return { address: recorded, forwarded: true };
|
|
106
|
+
} else if (peerAddress) TrustedProxy.#noteIgnoredPeer(headers, peerAddress);
|
|
107
|
+
return { address: peerAddress ? normalizeIpAddress(peerAddress) : null, forwarded: false };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
static #noteIgnoredPeer(headers: Headers, peerAddress: string) {
|
|
111
|
+
if (TrustedProxy.#warnedIgnoredPeer || !TrustedProxy.#load().strict) return;
|
|
112
|
+
if (!headers.has("x-forwarded-for") && !headers.has("x-real-ip")) return;
|
|
113
|
+
const bytes = IpLiteral.bytes(normalizeIpAddress(peerAddress));
|
|
114
|
+
if (!bytes || !TrustedProxy.#isPrivateRange(bytes)) return;
|
|
115
|
+
TrustedProxy.#warnedIgnoredPeer = true;
|
|
116
|
+
new Logger("TrustedProxy").warn(
|
|
117
|
+
`Forwarded headers from ${normalizeIpAddress(peerAddress)} are ignored: AKAN_TRUSTED_PROXIES does not list it. If it is your proxy, add its address or a CIDR that holds only your proxies.`,
|
|
118
|
+
);
|
|
59
119
|
}
|
|
60
120
|
|
|
61
121
|
/** For refusing an outbound fetch to a caller-chosen name: judges the address alone, never the proxy list. */
|
|
62
122
|
static isPrivateAddress(address: string): boolean {
|
|
63
|
-
const bytes =
|
|
123
|
+
const bytes = IpLiteral.bytes(normalizeIpAddress(address));
|
|
64
124
|
if (!bytes) return true;
|
|
65
|
-
if (TrustedProxy.#
|
|
125
|
+
if (TrustedProxy.#isLoopback(bytes) || TrustedProxy.#isPrivateRange(bytes)) return true;
|
|
66
126
|
if (bytes.length === 4) {
|
|
67
127
|
const [a = 0, b = 0] = bytes;
|
|
68
128
|
return a === 0 || (a === 100 && b >= 64 && b <= 127) || a >= 224;
|
|
@@ -70,31 +130,36 @@ export class TrustedProxy {
|
|
|
70
130
|
return bytes.every((byte) => byte === 0) || bytes[0] === 0xff;
|
|
71
131
|
}
|
|
72
132
|
|
|
73
|
-
|
|
74
|
-
|
|
133
|
+
static #isLoopback(bytes: Uint8Array): boolean {
|
|
134
|
+
if (bytes.length === 4) return bytes[0] === 127;
|
|
135
|
+
return bytes.every((byte, idx) => (idx === 15 ? byte === 1 : byte === 0));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** `10/8`, `172.16/12`, `192.168/16`, `169.254/16`, and their IPv6 counterparts `fc00::/7`, `fe80::/10`. */
|
|
139
|
+
static #isPrivateRange(bytes: Uint8Array): boolean {
|
|
75
140
|
if (bytes.length === 4) {
|
|
76
141
|
const [a = 0, b = 0] = bytes;
|
|
77
|
-
if (a === 10
|
|
142
|
+
if (a === 10) return true;
|
|
78
143
|
if (a === 192 && b === 168) return true;
|
|
79
144
|
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
80
145
|
return a === 169 && b === 254;
|
|
81
146
|
}
|
|
82
147
|
const [first = 0, second = 0] = bytes;
|
|
83
148
|
if ((first & 0xfe) === 0xfc) return true;
|
|
84
|
-
|
|
85
|
-
return bytes.every((byte, idx) => (idx === 15 ? byte === 1 : byte === 0));
|
|
149
|
+
return first === 0xfe && (second & 0xc0) === 0x80;
|
|
86
150
|
}
|
|
87
151
|
|
|
88
|
-
static #parseCidr(entry: string):
|
|
89
|
-
const [address, prefix] = entry.split("/");
|
|
90
|
-
|
|
152
|
+
static #parseCidr(entry: string): Cidr | null {
|
|
153
|
+
const [address, prefix, ...rest] = entry.split("/");
|
|
154
|
+
if (rest.length || (prefix !== undefined && !/^\d{1,3}$/.test(prefix))) return null;
|
|
155
|
+
const bytes = IpLiteral.bytes(normalizeIpAddress(address ?? ""));
|
|
91
156
|
if (!bytes) return null;
|
|
92
157
|
const bits = prefix === undefined ? bytes.length * 8 : Number(prefix);
|
|
93
158
|
if (!Number.isInteger(bits) || bits < 0 || bits > bytes.length * 8) return null;
|
|
94
159
|
return { bytes, bits };
|
|
95
160
|
}
|
|
96
161
|
|
|
97
|
-
static #inRange(bytes: Uint8Array, cidr:
|
|
162
|
+
static #inRange(bytes: Uint8Array, cidr: Cidr): boolean {
|
|
98
163
|
if (bytes.length !== cidr.bytes.length) return false;
|
|
99
164
|
const wholeBytes = cidr.bits >> 3;
|
|
100
165
|
for (let idx = 0; idx < wholeBytes; idx += 1) if (bytes[idx] !== cidr.bytes[idx]) return false;
|
|
@@ -103,40 +168,4 @@ export class TrustedProxy {
|
|
|
103
168
|
const mask = 0xff << (8 - restBits);
|
|
104
169
|
return ((bytes[wholeBytes] ?? 0) & mask) === ((cidr.bytes[wholeBytes] ?? 0) & mask);
|
|
105
170
|
}
|
|
106
|
-
|
|
107
|
-
static #toBytes(address: string): Uint8Array | null {
|
|
108
|
-
if (address.includes(".") && !address.includes(":")) {
|
|
109
|
-
const parts = address.split(".");
|
|
110
|
-
if (parts.length !== 4) return null;
|
|
111
|
-
const bytes = new Uint8Array(4);
|
|
112
|
-
for (const [idx, part] of parts.entries()) {
|
|
113
|
-
const value = Number(part);
|
|
114
|
-
if (!/^\d{1,3}$/.test(part) || value > 255) return null;
|
|
115
|
-
bytes[idx] = value;
|
|
116
|
-
}
|
|
117
|
-
return bytes;
|
|
118
|
-
}
|
|
119
|
-
return address.includes(":") ? TrustedProxy.#ipv6ToBytes(address) : null;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
static #ipv6ToBytes(address: string): Uint8Array | null {
|
|
123
|
-
|
|
124
|
-
const bare = address.split("%")[0] ?? "";
|
|
125
|
-
const halves = bare.split("::");
|
|
126
|
-
if (halves.length > 2) return null;
|
|
127
|
-
const groupsOf = (text: string) => (text ? text.split(":").filter((group) => group !== "") : []);
|
|
128
|
-
const head = groupsOf(halves[0] ?? "");
|
|
129
|
-
const tail = halves.length === 2 ? groupsOf(halves[1] ?? "") : [];
|
|
130
|
-
const filled = halves.length === 2 ? 8 - head.length - tail.length : 0;
|
|
131
|
-
if (filled < 0 || head.length + tail.length + filled !== 8) return null;
|
|
132
|
-
const groups = [...head, ...new Array(filled).fill("0"), ...tail];
|
|
133
|
-
const bytes = new Uint8Array(16);
|
|
134
|
-
for (const [idx, group] of groups.entries()) {
|
|
135
|
-
if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
|
|
136
|
-
const value = Number.parseInt(group, 16);
|
|
137
|
-
bytes[idx * 2] = value >> 8;
|
|
138
|
-
bytes[idx * 2 + 1] = value & 0xff;
|
|
139
|
-
}
|
|
140
|
-
return bytes;
|
|
141
|
-
}
|
|
142
171
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { getEnv } from "akanjs/base";
|
|
2
|
+
|
|
3
|
+
export class AppHosts {
|
|
4
|
+
static readonly #declared = new Set<string>();
|
|
5
|
+
|
|
6
|
+
static declare(hosts: Iterable<string>) {
|
|
7
|
+
for (const host of hosts) {
|
|
8
|
+
const name = AppHosts.nameOf(host);
|
|
9
|
+
if (name) AppHosts.#declared.add(name);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
static reset() {
|
|
14
|
+
AppHosts.#declared.clear();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
static allows(host: string, extra: Iterable<string> = []): boolean {
|
|
18
|
+
const name = AppHosts.nameOf(host);
|
|
19
|
+
if (!name) return false;
|
|
20
|
+
const { appName, environment, serveDomain } = getEnv();
|
|
21
|
+
if (name === AppHosts.nameOf(`${appName}-${environment}.${serveDomain}`) || AppHosts.#declared.has(name))
|
|
22
|
+
return true;
|
|
23
|
+
const listed = [...(process.env.AKAN_ALLOWED_HOSTS ?? "").split(","), ...extra];
|
|
24
|
+
return listed.some((entry) => AppHosts.nameOf(entry) === name);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
static nameOf(host: string): string | null {
|
|
28
|
+
const url = URL.parse(`http://${host.trim()}`);
|
|
29
|
+
if (!url || url.href !== `${url.origin}/`) return null;
|
|
30
|
+
return url.hostname.replace(/\.$/, "") || null;
|
|
31
|
+
}
|
|
32
|
+
}
|
package/common/authCookie.ts
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
|
|
2
2
|
|
|
3
|
-
/** The pre-scoping key.
|
|
3
|
+
/** The pre-scoping key. Never read or written; sign-in and sign-out still delete it from jars written before. */
|
|
4
4
|
export const legacyAuthTokenKey = "jwt";
|
|
5
5
|
|
|
6
|
-
/** Matches
|
|
7
|
-
export const isAuthTokenKey = (key: string): boolean =>
|
|
8
|
-
|
|
6
|
+
/** Matches every spelling, bare, app-scoped or `__Host-`, so a signout can sweep a jar written under any of them. */
|
|
7
|
+
export const isAuthTokenKey = (key: string): boolean => {
|
|
8
|
+
const name = key.startsWith("__Host-") ? key.slice("__Host-".length) : key;
|
|
9
|
+
return name === legacyAuthTokenKey || name.startsWith(`${legacyAuthTokenKey}:`);
|
|
10
|
+
};
|
|
9
11
|
|
|
10
|
-
const authCookiePattern = new RegExp(`(?:^|;\\s*)
|
|
12
|
+
const authCookiePattern = new RegExp(`(?:^|;\\s*)(?:__Host-)?${legacyAuthTokenKey}(?::[^=\\s;]+)?=`);
|
|
11
13
|
|
|
14
|
+
/** @deprecated Unused by the framework; parse the header with `CookieJar.parse` and test its `names()`. */
|
|
12
15
|
export const cookieHeaderHasAuthToken = (cookieHeader: string | null | undefined): boolean =>
|
|
13
16
|
!!cookieHeader && authCookiePattern.test(cookieHeader);
|
package/common/authToken.ts
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
1
|
import { getEnv } from "akanjs/base";
|
|
2
2
|
import { legacyAuthTokenKey } from "./authCookie";
|
|
3
|
+
import type { CookieJar } from "./cookieJar";
|
|
3
4
|
import { decodeJwtPayload } from "./jwtDecode";
|
|
4
5
|
|
|
5
|
-
export
|
|
6
|
+
export interface SessionRead {
|
|
7
|
+
token?: string;
|
|
8
|
+
duplicate?: { name: string; count: number };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const scopedAuthTokenKey = () => `${legacyAuthTokenKey}:${getEnv().appName}`;
|
|
12
|
+
|
|
13
|
+
export const authTokenKey = (): string =>
|
|
14
|
+
getEnv().operationMode === "local" ? scopedAuthTokenKey() : `__Host-${scopedAuthTokenKey()}`;
|
|
15
|
+
|
|
16
|
+
/** The names the session cookie went by before `authTokenKey()`; never read, and `initAuth`, sign-in and sign-out
|
|
17
|
+
* expire them. */
|
|
18
|
+
export const retiredAuthTokenKeys = (): string[] =>
|
|
19
|
+
[legacyAuthTokenKey, scopedAuthTokenKey()].filter((key) => key !== authTokenKey());
|
|
6
20
|
|
|
7
21
|
export const isOwnAuthToken = (jwt: string): boolean => {
|
|
8
22
|
const { appName, environment } = getEnv();
|
|
@@ -14,9 +28,13 @@ export const isOwnAuthToken = (jwt: string): boolean => {
|
|
|
14
28
|
}
|
|
15
29
|
};
|
|
16
30
|
|
|
17
|
-
export const
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
return
|
|
31
|
+
export const readSessionToken = (jar: CookieJar): SessionRead => {
|
|
32
|
+
const name = authTokenKey();
|
|
33
|
+
const { value, count } = jar.read(name);
|
|
34
|
+
if (count > 1) return { duplicate: { name, count } };
|
|
35
|
+
return value ? { token: value } : {};
|
|
22
36
|
};
|
|
37
|
+
|
|
38
|
+
/** @deprecated Reads the first value a lookup returns, so it cannot see a duplicated cookie; use `readSessionToken`. */
|
|
39
|
+
export const readAuthToken = (read: (key: string) => string | null | undefined): string | undefined =>
|
|
40
|
+
read(authTokenKey()) || undefined;
|
package/common/clientAddress.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { IpLiteral } from "./IpLiteral";
|
|
2
|
+
|
|
1
3
|
export const forwardedHeaders = [
|
|
2
4
|
"x-real-ip",
|
|
3
5
|
"x-forwarded-for",
|
|
@@ -6,18 +8,27 @@ export const forwardedHeaders = [
|
|
|
6
8
|
"x-forwarded-proto",
|
|
7
9
|
] as const;
|
|
8
10
|
|
|
9
|
-
export const normalizeIpAddress = (address: string): string =>
|
|
10
|
-
const trimmed = address.trim();
|
|
11
|
-
const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(trimmed);
|
|
12
|
-
return mapped?.[1] ?? trimmed;
|
|
13
|
-
};
|
|
11
|
+
export const normalizeIpAddress = (address: string): string => IpLiteral.normalize(address);
|
|
14
12
|
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Without `isTrusted`: `x-real-ip`, else the leftmost `x-forwarded-for` entry. With it: `x-forwarded-for` walked from
|
|
15
|
+
* the nearest hop past every address it vouches for, and `x-real-ip` only when there is none. `null`, never a
|
|
16
|
+
* placeholder, when nothing names an address.
|
|
17
|
+
*/
|
|
18
|
+
export const clientAddressFromHeaders = (headers: Headers, isTrusted?: (address: string) => boolean): string | null => {
|
|
19
|
+
const hops = (headers.get("x-forwarded-for") ?? "").split(",").filter((hop) => hop.trim());
|
|
20
|
+
const realIp = headers.get("x-real-ip");
|
|
21
|
+
if (!isTrusted) return (realIp ? IpLiteral.parse(realIp) : null) ?? (hops[0] ? IpLiteral.parse(hops[0]) : null);
|
|
22
|
+
let nearest: string | null = null;
|
|
23
|
+
for (const hop of hops.reverse()) {
|
|
24
|
+
const address = IpLiteral.parse(hop);
|
|
25
|
+
|
|
26
|
+
if (!address) break;
|
|
27
|
+
nearest = address;
|
|
28
|
+
if (!isTrusted(address)) return address;
|
|
29
|
+
}
|
|
30
|
+
if (nearest) return nearest;
|
|
31
|
+
return realIp ? IpLiteral.parse(realIp) : null;
|
|
21
32
|
};
|
|
22
33
|
|
|
23
34
|
export const clientPortFromHeaders = (headers: Headers): number | null => {
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
export interface CookieRead {
|
|
4
|
+
value?: string;
|
|
5
|
+
count: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface CookieEntry {
|
|
9
|
+
name: string;
|
|
10
|
+
value: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface CookieSegment extends CookieEntry {
|
|
14
|
+
raw: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class CookieJar {
|
|
18
|
+
readonly #segments: readonly CookieSegment[];
|
|
19
|
+
|
|
20
|
+
private constructor(segments: readonly CookieSegment[]) {
|
|
21
|
+
this.#segments = segments;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
static parse(header: string | null | undefined): CookieJar {
|
|
25
|
+
const segments: CookieSegment[] = [];
|
|
26
|
+
for (const part of header?.split(";") ?? []) {
|
|
27
|
+
const raw = part.trim();
|
|
28
|
+
const eq = raw.indexOf("=");
|
|
29
|
+
if (eq === -1) continue;
|
|
30
|
+
segments.push({ name: raw.slice(0, eq).trim(), value: CookieJar.#decode(raw.slice(eq + 1).trim()), raw });
|
|
31
|
+
}
|
|
32
|
+
return new CookieJar(segments);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
static #decode(text: string): string {
|
|
36
|
+
const unquoted = text.length >= 2 && text.startsWith('"') && text.endsWith('"') ? text.slice(1, -1) : text;
|
|
37
|
+
try {
|
|
38
|
+
return decodeURIComponent(unquoted);
|
|
39
|
+
} catch {
|
|
40
|
+
return unquoted;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
all(name: string): string[] {
|
|
45
|
+
return this.#segments.filter((segment) => segment.name === name).map((segment) => segment.value);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
read(name: string): CookieRead {
|
|
49
|
+
const values = this.all(name);
|
|
50
|
+
return values.length === 1 ? { value: values[0], count: 1 } : { count: values.length };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
has(name: string): boolean {
|
|
54
|
+
return this.#segments.some((segment) => segment.name === name);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
names(): string[] {
|
|
58
|
+
return [...new Set(this.#segments.map((segment) => segment.name))];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
entries(): CookieEntry[] {
|
|
62
|
+
return this.#segments.map(({ name, value }) => ({ name, value }));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
readJson(name: string): unknown {
|
|
66
|
+
const { value } = this.read(name);
|
|
67
|
+
if (!value?.startsWith("j:")) return value;
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(value.slice(2)) as unknown;
|
|
70
|
+
} catch {
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
toMap(): Map<string, CookieEntry> {
|
|
76
|
+
const counts = new Map<string, number>();
|
|
77
|
+
for (const { name } of this.#segments) counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
78
|
+
const map = new Map<string, CookieEntry>();
|
|
79
|
+
for (const { name, value } of this.#segments) if (counts.get(name) === 1) map.set(name, { name, value });
|
|
80
|
+
return map;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
without(drop: (name: string) => boolean): CookieJar {
|
|
84
|
+
return new CookieJar(this.#segments.filter((segment) => !drop(segment.name)));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
toHeader(): string {
|
|
88
|
+
return this.#segments.map((segment) => segment.raw).join("; ");
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
export interface CookieSweepTarget {
|
|
2
|
+
names: readonly string[];
|
|
3
|
+
host: string;
|
|
4
|
+
path: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export class CookieSweep {
|
|
8
|
+
static readonly #maxDepth = 4;
|
|
9
|
+
static readonly #maxPathLength = 128;
|
|
10
|
+
static readonly #maxParents = 4;
|
|
11
|
+
|
|
12
|
+
static setCookies({ names, host, path }: CookieSweepTarget): string[] {
|
|
13
|
+
const domains = CookieSweep.domains(host);
|
|
14
|
+
const paths = CookieSweep.pathPrefixes(path);
|
|
15
|
+
|
|
16
|
+
return names
|
|
17
|
+
.filter((name) => !name.startsWith("__Host-"))
|
|
18
|
+
.flatMap((name) =>
|
|
19
|
+
domains.flatMap((domain) =>
|
|
20
|
+
paths.flatMap((prefix) => {
|
|
21
|
+
const deletion = `${name}=; Domain=${domain}; Path=${prefix}; Max-Age=0; Secure; SameSite=Lax`;
|
|
22
|
+
return [deletion, `${deletion}; Partitioned`];
|
|
23
|
+
}),
|
|
24
|
+
),
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
static domains(host: string): string[] {
|
|
29
|
+
const labels = CookieSweep.#labelsOf(host);
|
|
30
|
+
return labels ? [labels.join("."), ...CookieSweep.#parentsOf(labels)] : [];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
static parentDomains(host: string): string[] {
|
|
34
|
+
const labels = CookieSweep.#labelsOf(host);
|
|
35
|
+
return labels ? CookieSweep.#parentsOf(labels) : [];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
static pathPrefixes(path: string): string[] {
|
|
39
|
+
const cut = path.search(/[^A-Za-z0-9\-._~!$&'()*+=:@%/]/);
|
|
40
|
+
const safe = path.startsWith("/") ? path.slice(0, cut === -1 ? path.length : cut) : "/";
|
|
41
|
+
const prefixes = new Set(["/"]);
|
|
42
|
+
const end = Math.min(safe.length, CookieSweep.#maxPathLength);
|
|
43
|
+
let depth = 0;
|
|
44
|
+
for (let idx = 1; idx < end && depth < CookieSweep.#maxDepth; idx++) {
|
|
45
|
+
if (safe[idx] !== "/") continue;
|
|
46
|
+
depth++;
|
|
47
|
+
prefixes.add(safe.slice(0, idx));
|
|
48
|
+
prefixes.add(safe.slice(0, idx + 1));
|
|
49
|
+
}
|
|
50
|
+
if (safe === path && depth < CookieSweep.#maxDepth && path.length <= CookieSweep.#maxPathLength) prefixes.add(path);
|
|
51
|
+
return [...prefixes];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
static #parentsOf(labels: string[]): string[] {
|
|
55
|
+
return labels
|
|
56
|
+
.slice(1, -1)
|
|
57
|
+
.map((_, idx) => labels.slice(idx + 1).join("."))
|
|
58
|
+
.slice(-CookieSweep.#maxParents);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
static #labelsOf(host: string): string[] | null {
|
|
62
|
+
const hostname = CookieSweep.#hostnameOf(host);
|
|
63
|
+
if (!hostname || hostname.length > 253) return null;
|
|
64
|
+
const labels = hostname.split(".");
|
|
65
|
+
if (labels.length < 2 || labels.some((label) => !label || label.length > 63)) return null;
|
|
66
|
+
return /^\d+$/.test(labels.at(-1) ?? "") ? null : labels;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
static #hostnameOf(host: string): string | null {
|
|
70
|
+
const trimmed = host.trim().toLowerCase();
|
|
71
|
+
if (!trimmed || trimmed.startsWith("[")) return null;
|
|
72
|
+
const colons = trimmed.split(":").length - 1;
|
|
73
|
+
if (colons > 1) return null;
|
|
74
|
+
const hostname = (colons === 1 ? trimmed.slice(0, trimmed.indexOf(":")) : trimmed).replace(/\.$/, "");
|
|
75
|
+
return /^[a-z0-9.-]+$/.test(hostname) ? hostname : null;
|
|
76
|
+
}
|
|
77
|
+
}
|
package/common/index.ts
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
|
+
export { AppHosts } from "./appHosts";
|
|
1
2
|
export { applyMixins, getAllPropertyDescriptors } from "./applyMixins";
|
|
2
3
|
export { cookieHeaderHasAuthToken, isAuthTokenKey, legacyAuthTokenKey } from "./authCookie";
|
|
3
|
-
export {
|
|
4
|
+
export {
|
|
5
|
+
authTokenKey,
|
|
6
|
+
isOwnAuthToken,
|
|
7
|
+
readAuthToken,
|
|
8
|
+
readSessionToken,
|
|
9
|
+
retiredAuthTokenKeys,
|
|
10
|
+
type SessionRead,
|
|
11
|
+
} from "./authToken";
|
|
4
12
|
export { Backoff, type BackoffPolicy } from "./backoff";
|
|
5
13
|
export { bearerTokenOf } from "./bearerTokenOf";
|
|
6
14
|
export { CodeAgentClient, type CodeAgentTransport } from "./CodeAgentClient";
|
|
@@ -64,6 +72,8 @@ export {
|
|
|
64
72
|
codeAgentWireVersion,
|
|
65
73
|
isCodeAgentReply,
|
|
66
74
|
} from "./codeAgentWire";
|
|
75
|
+
export { type CookieEntry, CookieJar, type CookieRead } from "./cookieJar";
|
|
76
|
+
export { CookieSweep, type CookieSweepTarget } from "./cookieSweep";
|
|
67
77
|
export { EventStream, type EventStreamOptions } from "./eventStream";
|
|
68
78
|
export {
|
|
69
79
|
type FileUploadCapability,
|
|
@@ -163,6 +173,8 @@ export {
|
|
|
163
173
|
} from "./pipelinePlan";
|
|
164
174
|
export { type RouteLayer, RouteLayering } from "./RouteLayering";
|
|
165
175
|
export { randomPick, randomPicks } from "./randomPick";
|
|
176
|
+
export { RemoteAuthCode } from "./remoteAuthCode";
|
|
177
|
+
export { RequestLocale, type RequestLocaleInput } from "./requestLocale";
|
|
166
178
|
export { hostFromRequest, isJsonContentType, originFromRequest } from "./requestOrigin";
|
|
167
179
|
export { RestClient, type RestClientOptions, type RestRequestOptions } from "./restClient";
|
|
168
180
|
export { round } from "./round";
|
|
@@ -189,6 +201,7 @@ export {
|
|
|
189
201
|
validatePageSourceFile,
|
|
190
202
|
validateSubRoutePageKey,
|
|
191
203
|
} from "./routeConvention";
|
|
204
|
+
export { type SessionCookieDuplicate, SessionCookies } from "./sessionCookies";
|
|
192
205
|
export { sleep } from "./sleep";
|
|
193
206
|
export { getBasePathFromPathname, parseBasePaths, parseSubRouteHosts, resolveSubRouteHosts } from "./subRoute";
|
|
194
207
|
export { TrustedProxy } from "./TrustedProxy";
|