@ocap/chain-node 1.32.1 → 1.32.3

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.
@@ -0,0 +1,155 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
3
+ let node_net = require("node:net");
4
+ node_net = require_rolldown_runtime.__toESM(node_net);
5
+ let _ocap_resolver = require("@ocap/resolver");
6
+
7
+ //#region src/mesh-egress.ts
8
+ /**
9
+ * Strict validation and connect-time SSRF guard for `ARC_MESH_EGRESS_URL` / `profile.meshEgressUrl`
10
+ * (`@ocap/chain-node`, #2025).
11
+ *
12
+ * Allows outbound follower sync / consensus peer fetches to reach ONLY the pinned local
13
+ * `afs-mesh` loopback gateway (`http://127.0.0.1:<port>` or `http://[::1]:<port>`) with
14
+ * `redirect: 'error'`, while keeping `169.254.169.254`, `0.0.0.0`, `localhost`, and every
15
+ * other loopback / RFC1918 host:port 100% blocked unless `allowPrivatePeers` is enabled.
16
+ */
17
+ const MESH_EGRESS_RAW_RE = /^http:\/\/(127\.0\.0\.1|\[::1\]):([1-9]\d{0,4})\/?$/i;
18
+ /**
19
+ * Parse and strictly validate `ARC_MESH_EGRESS_URL` / `meshEgressUrl` at config parse time.
20
+ * Must be `http:` on literal `127.0.0.1` or `[::1]` with an explicit port `1..65535`,
21
+ * no credentials, no subpath, and no query/hash.
22
+ */
23
+ function parseMeshEgressUrl(rawUrl, label = "ARC_MESH_EGRESS_URL") {
24
+ if (rawUrl === void 0 || rawUrl === null) return null;
25
+ if (typeof rawUrl !== "string") throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label}: expected URL string`);
26
+ const trimmed = rawUrl.trim();
27
+ if (!trimmed) return null;
28
+ for (let i = 0; i < rawUrl.length; i++) {
29
+ const code = rawUrl.charCodeAt(i);
30
+ if (code < 32 || code === 127) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label}: control characters are forbidden`);
31
+ }
32
+ if (/\s/.test(trimmed) || trimmed.includes("@") || trimmed.includes("\\") || trimmed.includes("?") || trimmed.includes("#")) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label}="${trimmed}": must be http://127.0.0.1:<port> or http://[::1]:<port> with no credentials, query, or hash`);
33
+ const match = MESH_EGRESS_RAW_RE.exec(trimmed);
34
+ if (!match) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label}="${trimmed}": expected http://127.0.0.1:<port> or http://[::1]:<port> with explicit port 1..65535`);
35
+ const hostname = match[1].toLowerCase();
36
+ const port = Number(match[2]);
37
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label}="${trimmed}": port must be in 1..65535`);
38
+ const normalizedUrl = `http://${hostname}:${port}`;
39
+ return {
40
+ normalizedUrl,
41
+ origin: new URL(normalizedUrl).origin.toLowerCase(),
42
+ hostname,
43
+ port
44
+ };
45
+ }
46
+ function extractRawAuthority(rawUrl) {
47
+ const schemeSep = rawUrl.indexOf("://");
48
+ if (schemeSep < 0) return null;
49
+ const afterScheme = rawUrl.slice(schemeSep + 3);
50
+ const slashIdx = afterScheme.search(/[/?#]/);
51
+ const authority = slashIdx >= 0 ? afterScheme.slice(0, slashIdx) : afterScheme;
52
+ if (!authority || authority.includes("@") || authority.includes("\\")) return null;
53
+ if (authority.startsWith("[")) {
54
+ const closeBracket = authority.indexOf("]");
55
+ if (closeBracket < 0) return null;
56
+ const rawHost = authority.slice(0, closeBracket + 1);
57
+ const tail = authority.slice(closeBracket + 1);
58
+ if (!tail) return {
59
+ rawHost,
60
+ rawPort: null
61
+ };
62
+ if (!tail.startsWith(":")) return null;
63
+ return {
64
+ rawHost,
65
+ rawPort: tail.slice(1)
66
+ };
67
+ }
68
+ const colonIdx = authority.indexOf(":");
69
+ if (colonIdx < 0) return {
70
+ rawHost: authority,
71
+ rawPort: null
72
+ };
73
+ if (authority.indexOf(":", colonIdx + 1) >= 0) return null;
74
+ return {
75
+ rawHost: authority.slice(0, colonIdx),
76
+ rawPort: authority.slice(colonIdx + 1)
77
+ };
78
+ }
79
+ function isExactMeshEgressTarget(rawUrl, parsed, meshEgress) {
80
+ if (parsed.protocol !== "http:") return false;
81
+ if (parsed.username || parsed.password) return false;
82
+ if (parsed.origin.toLowerCase() !== meshEgress.origin) return false;
83
+ const auth = extractRawAuthority(rawUrl);
84
+ if (!auth) return false;
85
+ if (auth.rawHost.toLowerCase() !== meshEgress.hostname) return false;
86
+ if (!auth.rawPort || !/^[1-9]\d{0,4}$/.test(auth.rawPort)) return false;
87
+ if (Number(auth.rawPort) !== meshEgress.port) return false;
88
+ const rawPath = rawUrl.slice(rawUrl.indexOf("://") + 3);
89
+ const pathStart = rawPath.indexOf("/");
90
+ if (pathStart >= 0) {
91
+ const pathAndQuery = rawPath.slice(pathStart);
92
+ const qIdx = pathAndQuery.search(/[?#]/);
93
+ const pathnameOnly = qIdx >= 0 ? pathAndQuery.slice(0, qIdx) : pathAndQuery;
94
+ if (pathnameOnly.includes("\\") || pathnameOnly.includes("//") || /(?:^|\/)\.\.(?:\/|$)/.test(pathnameOnly) || /%(?:25)*(?:2e|2f|5c|00)/i.test(pathnameOnly)) return false;
95
+ }
96
+ return true;
97
+ }
98
+ function isForbiddenInternalOrPrivateHost(parsed) {
99
+ const bareHost = parsed.hostname.replace(/^\[|\]$/g, "").replace(/\.+$/g, "").toLowerCase();
100
+ if (!bareHost || bareHost === "localhost" || bareHost.endsWith(".localhost") || bareHost === "metadata.google.internal" || bareHost.endsWith(".internal") || bareHost === "0.0.0.0") return true;
101
+ if (node_net.default.isIP(bareHost) !== 0) return (0, _ocap_resolver.isPrivateOrReservedIpAddress)(bareHost);
102
+ if (/^\d+$/.test(bareHost) || /^0x[0-9a-f]+$/i.test(bareHost)) return true;
103
+ return false;
104
+ }
105
+ /**
106
+ * Create a connect-time SSRF guard for `@ocap/chain-node` outbound peer requests
107
+ * that pins local loopback access exclusively to `meshEgress` (`redirect: 'error'`)
108
+ * when `allowPrivatePeers` is false.
109
+ */
110
+ function createChainNodePeerFetchGuard(options) {
111
+ const allowPrivate = Boolean(options.allowPrivatePeers);
112
+ const meshEgress = options.meshEgress ?? null;
113
+ const baseFetch = options.baseFetch ?? globalThis.fetch;
114
+ const safePublicStaticUrls = (options.trustedStaticUrls ?? []).filter((raw) => {
115
+ if (!raw || !String(raw).trim()) return false;
116
+ if (allowPrivate) return true;
117
+ try {
118
+ const trimmed = String(raw).trim();
119
+ const parsed = new URL(trimmed);
120
+ if (meshEgress && isExactMeshEgressTarget(trimmed, parsed, meshEgress)) return false;
121
+ return !isForbiddenInternalOrPrivateHost(parsed);
122
+ } catch {
123
+ return false;
124
+ }
125
+ });
126
+ const innerGuard = (0, _ocap_resolver.createFollowerPeerFetchGuard)({
127
+ env: { ALLOW_PRIVATE_PEER_URLS: allowPrivate ? "1" : "0" },
128
+ dnsLookup: options.dnsLookup,
129
+ trustedStaticUrls: safePublicStaticUrls,
130
+ baseFetch
131
+ });
132
+ return (async (input, init) => {
133
+ const safeInit = {
134
+ ...init,
135
+ redirect: "error"
136
+ };
137
+ if (allowPrivate) return baseFetch(input, safeInit);
138
+ const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
139
+ let parsed;
140
+ try {
141
+ parsed = new URL(urlStr);
142
+ } catch {
143
+ throw new _ocap_util_lib_error.CustomError("INVALID_PARAMS", `Invalid outbound peer URL: ${urlStr}`);
144
+ }
145
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new _ocap_util_lib_error.CustomError("SSRF_FORBIDDEN_PEER_URL", `Unsupported outbound peer URL protocol: ${parsed.protocol}`);
146
+ if (parsed.username || parsed.password || !extractRawAuthority(urlStr)) throw new _ocap_util_lib_error.CustomError("SSRF_FORBIDDEN_PEER_URL", "Outbound peer URL must not embed credentials or malformed host");
147
+ if (meshEgress && isExactMeshEgressTarget(urlStr, parsed, meshEgress)) return baseFetch(input, safeInit);
148
+ if (isForbiddenInternalOrPrivateHost(parsed)) throw new _ocap_util_lib_error.CustomError("SSRF_FORBIDDEN_PEER_URL", `Connect-time SSRF guard blocked non-mesh internal/private target "${parsed.origin}"`);
149
+ return innerGuard(input, safeInit);
150
+ });
151
+ }
152
+
153
+ //#endregion
154
+ exports.createChainNodePeerFetchGuard = createChainNodePeerFetchGuard;
155
+ exports.parseMeshEgressUrl = parseMeshEgressUrl;
@@ -0,0 +1,30 @@
1
+ import { DnsLookupAllFn } from "@ocap/resolver";
2
+
3
+ //#region src/mesh-egress.d.ts
4
+
5
+ interface ValidatedMeshEgress {
6
+ readonly normalizedUrl: string;
7
+ readonly origin: string;
8
+ readonly hostname: '127.0.0.1' | '[::1]';
9
+ readonly port: number;
10
+ }
11
+ /**
12
+ * Parse and strictly validate `ARC_MESH_EGRESS_URL` / `meshEgressUrl` at config parse time.
13
+ * Must be `http:` on literal `127.0.0.1` or `[::1]` with an explicit port `1..65535`,
14
+ * no credentials, no subpath, and no query/hash.
15
+ */
16
+ declare function parseMeshEgressUrl(rawUrl: string | undefined | null, label?: string): ValidatedMeshEgress | null;
17
+ /**
18
+ * Create a connect-time SSRF guard for `@ocap/chain-node` outbound peer requests
19
+ * that pins local loopback access exclusively to `meshEgress` (`redirect: 'error'`)
20
+ * when `allowPrivatePeers` is false.
21
+ */
22
+ declare function createChainNodePeerFetchGuard(options: {
23
+ allowPrivatePeers?: boolean;
24
+ meshEgress?: ValidatedMeshEgress | null;
25
+ trustedStaticUrls?: Array<string | undefined | null>;
26
+ dnsLookup?: DnsLookupAllFn;
27
+ baseFetch?: typeof fetch;
28
+ }): typeof fetch;
29
+ //#endregion
30
+ export { ValidatedMeshEgress, createChainNodePeerFetchGuard, parseMeshEgressUrl };