@ocap/resolver 1.31.9 → 1.32.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/esm/_virtual/rolldown_runtime.mjs +7 -0
- package/esm/api.d.mts +33 -5
- package/esm/api.mjs +939 -53
- package/esm/dashboard.d.mts +199 -0
- package/esm/dashboard.mjs +2481 -0
- package/esm/explorer.d.mts +29 -0
- package/esm/explorer.mjs +227 -0
- package/esm/follower.d.mts +294 -0
- package/esm/follower.mjs +2452 -0
- package/esm/hooks.mjs +1 -1
- package/esm/hotstuff-runtime.d.mts +271 -0
- package/esm/hotstuff-runtime.mjs +2668 -0
- package/esm/index.d.mts +79 -4
- package/esm/index.mjs +911 -174
- package/esm/node-preferences.d.mts +203 -0
- package/esm/node-preferences.mjs +1021 -0
- package/esm/replayer.d.mts +114 -0
- package/esm/replayer.mjs +430 -0
- package/esm/token-distribution.mjs +2 -2
- package/esm/token-flow.mjs +1 -1
- package/esm/types.d.mts +25 -2
- package/lib/api.cjs +941 -52
- package/lib/api.d.cts +33 -5
- package/lib/dashboard.cjs +2491 -0
- package/lib/dashboard.d.cts +199 -0
- package/lib/explorer.cjs +227 -0
- package/lib/explorer.d.cts +29 -0
- package/lib/follower.cjs +2458 -0
- package/lib/follower.d.cts +294 -0
- package/lib/hooks.cjs +1 -1
- package/lib/hotstuff-runtime.cjs +2671 -0
- package/lib/hotstuff-runtime.d.cts +271 -0
- package/lib/index.cjs +946 -174
- package/lib/index.d.cts +79 -4
- package/lib/node-preferences.cjs +1043 -0
- package/lib/node-preferences.d.cts +203 -0
- package/lib/replayer.cjs +432 -0
- package/lib/replayer.d.cts +114 -0
- package/lib/token-distribution.cjs +2 -2
- package/lib/token-flow.cjs +1 -1
- package/lib/types.d.cts +25 -2
- package/package.json +20 -14
|
@@ -0,0 +1,1021 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as crypto from "node:crypto";
|
|
4
|
+
import * as dns from "node:dns";
|
|
5
|
+
import * as net from "node:net";
|
|
6
|
+
import { isValid } from "@arcblock/did";
|
|
7
|
+
import { resolveClientIp } from "@ocap/util/lib/client-ip";
|
|
8
|
+
|
|
9
|
+
//#region src/node-preferences.ts
|
|
10
|
+
/**
|
|
11
|
+
* Auxiliary Node Preferences, Hot-Reloadable Runtime Config & Constant-Time Admin Auth (#1756)
|
|
12
|
+
*
|
|
13
|
+
* Replaces sunset `blocklet.prefs.json` Formily preferences with a self-contained,
|
|
14
|
+
* schema-validated, atomically persisted (`0o600` `.tmp` + `fsync` + `rename`)
|
|
15
|
+
* configuration manager backed by `<dataDir>/preferences.json` (or `CHAIN_PREFERENCES_PATH`).
|
|
16
|
+
*/
|
|
17
|
+
const MAX_BLOCKED_ACCOUNTS = 5e3;
|
|
18
|
+
const MAX_TRUSTED_ACCOUNTS = 1e3;
|
|
19
|
+
const MAX_RESERVED_SYMBOLS = 500;
|
|
20
|
+
const MAX_PEER_URLS = 32;
|
|
21
|
+
const MAX_MEMO_LENGTH = 256;
|
|
22
|
+
const MAX_CONFIG_BODY_BYTES = 32 * 1024;
|
|
23
|
+
var NodePreferencesError = class extends Error {
|
|
24
|
+
constructor(code, message, status = 400) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = "NodePreferencesError";
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.status = status;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Constant-time token comparison over fixed-width SHA-256 digests so secret length is never leaked.
|
|
33
|
+
*/
|
|
34
|
+
function timingSafeTokenEqual(expected, provided) {
|
|
35
|
+
const validExpected = typeof expected === "string" && expected.length > 0;
|
|
36
|
+
const validProvided = typeof provided === "string" && provided.length > 0;
|
|
37
|
+
const digestA = crypto.createHash("sha256").update(validExpected ? expected : "invalid-expected-placeholder", "utf8").digest();
|
|
38
|
+
const digestB = crypto.createHash("sha256").update(validProvided ? provided : "invalid-provided-placeholder", "utf8").digest();
|
|
39
|
+
const matched = crypto.timingSafeEqual(digestA, digestB);
|
|
40
|
+
return validExpected && validProvided && matched;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Normalize DID / 0x / did:name address keys identically to HTTP `/blocked` lookup.
|
|
44
|
+
*/
|
|
45
|
+
function normalizeBlockedAccountKey(raw) {
|
|
46
|
+
if (typeof raw !== "string") return "";
|
|
47
|
+
const trimmed = raw.trim();
|
|
48
|
+
if (!trimmed) return "";
|
|
49
|
+
const match = /^did:([^:]+):/i.exec(trimmed);
|
|
50
|
+
const addr = trimmed.replace(/^did:[^:]+:/i, "");
|
|
51
|
+
if (!addr) return "";
|
|
52
|
+
if (match && match[1].toLowerCase() === "name") return `name:${addr.normalize("NFC").toLowerCase()}`;
|
|
53
|
+
return `addr:${/^0x[0-9a-fA-F]+$/i.test(addr) ? addr.toLowerCase() : addr}`;
|
|
54
|
+
}
|
|
55
|
+
function sanitizeMemo(raw) {
|
|
56
|
+
if (raw === void 0 || raw === null) return void 0;
|
|
57
|
+
if (typeof raw !== "string") throw new NodePreferencesError("INVALID_PARAMS", "memo must be a string", 400);
|
|
58
|
+
let cleaned = "";
|
|
59
|
+
for (let i = 0; i < raw.length; i++) {
|
|
60
|
+
const code = raw.charCodeAt(i);
|
|
61
|
+
if (code === 9 || code >= 32 && code !== 127 && (code < 128 || code > 159)) cleaned += raw[i];
|
|
62
|
+
}
|
|
63
|
+
const trimmed = cleaned.trim();
|
|
64
|
+
if (trimmed.length > MAX_MEMO_LENGTH) throw new NodePreferencesError("INVALID_PARAMS", `memo exceeds maximum length of ${MAX_MEMO_LENGTH}`, 400);
|
|
65
|
+
return trimmed || void 0;
|
|
66
|
+
}
|
|
67
|
+
function isValidAccountAddressCandidate(raw) {
|
|
68
|
+
if (typeof raw !== "string") return false;
|
|
69
|
+
const trimmed = raw.trim();
|
|
70
|
+
if (!trimmed || trimmed.length > 160) return false;
|
|
71
|
+
if (/[\s<>"'`\\]/.test(trimmed)) return false;
|
|
72
|
+
if (/^did:name:[A-Za-z0-9_.-]{1,128}$/i.test(trimmed)) return true;
|
|
73
|
+
if (/^(?:did:[a-z0-9]+:)?0x[0-9a-fA-F]{16,64}$/i.test(trimmed)) return true;
|
|
74
|
+
if (isValid(trimmed.replace(/^did:[^:]+:/i, ""))) return true;
|
|
75
|
+
return /^(?:did:[a-z0-9]+:)?z[1-9A-HJ-NP-Za-km-z]{2,64}$/.test(trimmed);
|
|
76
|
+
}
|
|
77
|
+
function parseCsvEnv(raw) {
|
|
78
|
+
return String(raw || "").split(",").map((item) => item.trim()).filter(Boolean);
|
|
79
|
+
}
|
|
80
|
+
function isPrivateOrReservedIpv4(ip) {
|
|
81
|
+
const parts = ip.split(".").map((octet) => Number(octet));
|
|
82
|
+
if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;
|
|
83
|
+
const [a, b, c] = parts;
|
|
84
|
+
if (a === 0) return true;
|
|
85
|
+
if (a === 10) return true;
|
|
86
|
+
if (a === 127) return true;
|
|
87
|
+
if (a === 169 && b === 254) return true;
|
|
88
|
+
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
89
|
+
if (a === 192 && b === 168) return true;
|
|
90
|
+
if (a === 100 && b >= 64 && b <= 127) return true;
|
|
91
|
+
if (a === 192 && b === 0 && (c === 0 || c === 2)) return true;
|
|
92
|
+
if (a === 198 && (b === 18 || b === 19)) return true;
|
|
93
|
+
if (a === 198 && b === 51 && c === 100) return true;
|
|
94
|
+
if (a === 203 && b === 0 && c === 113) return true;
|
|
95
|
+
if (a >= 224) return true;
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
function ipv4GroupsToDotted(hi, lo) {
|
|
99
|
+
return `${hi >>> 8 & 255}.${hi & 255}.${lo >>> 8 & 255}.${lo & 255}`;
|
|
100
|
+
}
|
|
101
|
+
function parseIpv6ToGroups(rawIp) {
|
|
102
|
+
let str = rawIp.trim().toLowerCase();
|
|
103
|
+
if (!str) return null;
|
|
104
|
+
const lastColon = str.lastIndexOf(":");
|
|
105
|
+
if (lastColon !== -1 && str.indexOf(".", lastColon) !== -1) {
|
|
106
|
+
const v4Part = str.slice(lastColon + 1);
|
|
107
|
+
if (net.isIP(v4Part) !== 4) return null;
|
|
108
|
+
const octets = v4Part.split(".").map((x) => Number(x));
|
|
109
|
+
const hi = (octets[0] << 8 | octets[1]).toString(16);
|
|
110
|
+
const lo = (octets[2] << 8 | octets[3]).toString(16);
|
|
111
|
+
str = `${str.slice(0, lastColon)}:${hi}:${lo}`;
|
|
112
|
+
}
|
|
113
|
+
const dblIdx = str.indexOf("::");
|
|
114
|
+
if (dblIdx !== -1) {
|
|
115
|
+
if (str.indexOf("::", dblIdx + 2) !== -1) return null;
|
|
116
|
+
const leftRaw = str.slice(0, dblIdx);
|
|
117
|
+
const rightRaw = str.slice(dblIdx + 2);
|
|
118
|
+
const leftParts = leftRaw ? leftRaw.split(":") : [];
|
|
119
|
+
const rightParts = rightRaw ? rightRaw.split(":") : [];
|
|
120
|
+
const missing = 8 - (leftParts.length + rightParts.length);
|
|
121
|
+
if (missing < 1) return null;
|
|
122
|
+
const full = [
|
|
123
|
+
...leftParts,
|
|
124
|
+
...Array(missing).fill("0"),
|
|
125
|
+
...rightParts
|
|
126
|
+
];
|
|
127
|
+
if (full.length !== 8) return null;
|
|
128
|
+
const out$1 = new Uint16Array(8);
|
|
129
|
+
for (let i = 0; i < 8; i++) {
|
|
130
|
+
if (!/^[0-9a-f]{1,4}$/.test(full[i])) return null;
|
|
131
|
+
out$1[i] = Number.parseInt(full[i], 16);
|
|
132
|
+
}
|
|
133
|
+
return out$1;
|
|
134
|
+
}
|
|
135
|
+
const parts = str.split(":");
|
|
136
|
+
if (parts.length !== 8) return null;
|
|
137
|
+
const out = new Uint16Array(8);
|
|
138
|
+
for (let i = 0; i < 8; i++) {
|
|
139
|
+
if (!/^[0-9a-f]{1,4}$/.test(parts[i])) return null;
|
|
140
|
+
out[i] = Number.parseInt(parts[i], 16);
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
function isPrivateOrReservedIpAddress(rawIp) {
|
|
145
|
+
const ip = rawIp.trim().replace(/^\[|\]$/g, "").split("%")[0];
|
|
146
|
+
const version = net.isIP(ip);
|
|
147
|
+
if (version === 4) return isPrivateOrReservedIpv4(ip);
|
|
148
|
+
if (version === 6) {
|
|
149
|
+
const g = parseIpv6ToGroups(ip);
|
|
150
|
+
if (!g) return true;
|
|
151
|
+
if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 0) return true;
|
|
152
|
+
if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 65535) return isPrivateOrReservedIpv4(ipv4GroupsToDotted(g[6], g[7]));
|
|
153
|
+
if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 65535 && g[5] === 0) return isPrivateOrReservedIpv4(ipv4GroupsToDotted(g[6], g[7]));
|
|
154
|
+
if (g[0] === 100 && g[1] === 65435) {
|
|
155
|
+
if (g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 0) return isPrivateOrReservedIpv4(ipv4GroupsToDotted(g[6], g[7]));
|
|
156
|
+
if (g[2] === 1) return true;
|
|
157
|
+
}
|
|
158
|
+
if (g[0] === 256 && g[1] === 0 && g[2] === 0 && g[3] === 0) return true;
|
|
159
|
+
if (g[0] === 8193 && g[1] <= 511) return true;
|
|
160
|
+
if (g[0] === 8193 && g[1] === 3512) return true;
|
|
161
|
+
if (g[0] === 8194) return true;
|
|
162
|
+
if ((g[0] & 65024) === 64512) return true;
|
|
163
|
+
if ((g[0] & 65472) === 65152) return true;
|
|
164
|
+
if ((g[0] & 65280) === 65280) return true;
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
function isAllowPrivatePeerUrlsEnabled(env) {
|
|
170
|
+
const raw = String(env.ALLOW_PRIVATE_PEER_URLS ?? "").trim().toLowerCase();
|
|
171
|
+
return raw === "1" || raw === "true";
|
|
172
|
+
}
|
|
173
|
+
const defaultDnsLookupAll = async (hostname) => {
|
|
174
|
+
return dns.promises.lookup(hostname, {
|
|
175
|
+
all: true,
|
|
176
|
+
verbatim: true
|
|
177
|
+
});
|
|
178
|
+
};
|
|
179
|
+
/**
|
|
180
|
+
* Validate Follower `peerUrls` for strict HTTP(S) base URL hygiene and SSRF / DNS-rebinding safety.
|
|
181
|
+
*/
|
|
182
|
+
async function validateFollowerPeerUrls(rawUrls, env = process.env, dnsLookup = defaultDnsLookupAll) {
|
|
183
|
+
if (!Array.isArray(rawUrls)) throw new NodePreferencesError("INVALID_PARAMS", "runtime.peerUrls must be an array of HTTP(S) URLs", 400);
|
|
184
|
+
if (rawUrls.length > MAX_PEER_URLS) throw new NodePreferencesError("INVALID_PARAMS", `runtime.peerUrls cannot exceed ${MAX_PEER_URLS} entries`, 400);
|
|
185
|
+
const allowPrivate = isAllowPrivatePeerUrlsEnabled(env);
|
|
186
|
+
const normalized = [];
|
|
187
|
+
const seen = /* @__PURE__ */ new Set();
|
|
188
|
+
for (const item of rawUrls) {
|
|
189
|
+
if (typeof item !== "string" || !item.trim()) throw new NodePreferencesError("INVALID_PARAMS", "Each peerUrl must be a non-empty URL string", 400);
|
|
190
|
+
let parsed;
|
|
191
|
+
try {
|
|
192
|
+
parsed = new URL(item.trim());
|
|
193
|
+
} catch {
|
|
194
|
+
throw new NodePreferencesError("INVALID_PARAMS", `Invalid peerUrl: ${item}`, 400);
|
|
195
|
+
}
|
|
196
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new NodePreferencesError("INVALID_PARAMS", `Unsupported peerUrl protocol: ${parsed.protocol}`, 400);
|
|
197
|
+
if (parsed.username || parsed.password) throw new NodePreferencesError("INVALID_PARAMS", "peerUrl must not contain userinfo credentials", 400);
|
|
198
|
+
if (parsed.search || parsed.hash) throw new NodePreferencesError("INVALID_PARAMS", "peerUrl must not contain query string or hash fragment", 400);
|
|
199
|
+
const hostname = parsed.hostname.replace(/^\[|\]$/g, "").replace(/\.+$/g, "").toLowerCase();
|
|
200
|
+
if (!hostname) throw new NodePreferencesError("INVALID_PARAMS", `Invalid peerUrl hostname: ${item}`, 400);
|
|
201
|
+
if (!allowPrivate) {
|
|
202
|
+
if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "metadata.google.internal" || hostname.endsWith(".internal")) throw new NodePreferencesError("SSRF_FORBIDDEN_PEER_URL", `Private or internal peerUrl host "${hostname}" is forbidden unless ALLOW_PRIVATE_PEER_URLS=1`, 400);
|
|
203
|
+
if (net.isIP(hostname) !== 0) {
|
|
204
|
+
if (isPrivateOrReservedIpAddress(hostname)) throw new NodePreferencesError("SSRF_FORBIDDEN_PEER_URL", `Private, loopback, or metadata IP "${hostname}" is forbidden unless ALLOW_PRIVATE_PEER_URLS=1`, 400);
|
|
205
|
+
} else {
|
|
206
|
+
let resolvedAddrs;
|
|
207
|
+
try {
|
|
208
|
+
resolvedAddrs = await dnsLookup(hostname);
|
|
209
|
+
} catch {
|
|
210
|
+
throw new NodePreferencesError("SSRF_DNS_RESOLUTION_FAILED", `Unable to resolve peerUrl hostname "${hostname}"`, 400);
|
|
211
|
+
}
|
|
212
|
+
if (!Array.isArray(resolvedAddrs) || resolvedAddrs.length === 0) throw new NodePreferencesError("SSRF_DNS_RESOLUTION_FAILED", `Hostname "${hostname}" returned no DNS records`, 400);
|
|
213
|
+
for (const record of resolvedAddrs) if (!record?.address || isPrivateOrReservedIpAddress(record.address)) throw new NodePreferencesError("SSRF_FORBIDDEN_PEER_URL", `Hostname "${hostname}" resolves to forbidden private/reserved IP "${record?.address || "unknown"}"`, 400);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const cleanUrl = parsed.toString().replace(/\/+$/g, "");
|
|
217
|
+
if (!seen.has(cleanUrl)) {
|
|
218
|
+
seen.add(cleanUrl);
|
|
219
|
+
normalized.push(cleanUrl);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return normalized;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Connect-time SSRF & DNS-rebinding guard for Follower / LeaderRouter outbound `fetch()` calls.
|
|
226
|
+
* Static operator-configured origins (`UPSTREAM_CHAIN_URL` / `CLUSTER_PEER_URLS` / `HOTSTUFF_VALIDATORS` from boot env)
|
|
227
|
+
* are explicitly allowlisted; any dynamically configured `peerUrl` is re-verified on every request (defeating `TTL=0`
|
|
228
|
+
* DNS rebinding) and, for `http:` DNS hosts, connected directly to the verified public IP with an explicit `Host` header
|
|
229
|
+
* so no second DNS resolution occurs.
|
|
230
|
+
*/
|
|
231
|
+
function createFollowerPeerFetchGuard(options) {
|
|
232
|
+
const env = options.env ?? process.env;
|
|
233
|
+
const dnsLookup = options.dnsLookup ?? defaultDnsLookupAll;
|
|
234
|
+
const baseFetch = options.baseFetch ?? fetch;
|
|
235
|
+
const trustedOrigins = /* @__PURE__ */ new Set();
|
|
236
|
+
for (const raw of options.trustedStaticUrls ?? []) {
|
|
237
|
+
if (!raw || !String(raw).trim()) continue;
|
|
238
|
+
try {
|
|
239
|
+
trustedOrigins.add(new URL(String(raw).trim()).origin.toLowerCase());
|
|
240
|
+
} catch {}
|
|
241
|
+
}
|
|
242
|
+
return (async (input, init) => {
|
|
243
|
+
const safeInit = {
|
|
244
|
+
...init,
|
|
245
|
+
redirect: "error"
|
|
246
|
+
};
|
|
247
|
+
if (isAllowPrivatePeerUrlsEnabled(env)) return baseFetch(input, safeInit);
|
|
248
|
+
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
249
|
+
let parsed;
|
|
250
|
+
try {
|
|
251
|
+
parsed = new URL(urlStr);
|
|
252
|
+
} catch {
|
|
253
|
+
throw new NodePreferencesError("INVALID_PARAMS", `Invalid outbound peer URL: ${urlStr}`, 400);
|
|
254
|
+
}
|
|
255
|
+
if (trustedOrigins.has(parsed.origin.toLowerCase())) return baseFetch(input, safeInit);
|
|
256
|
+
const hostname = parsed.hostname.replace(/^\[|\]$/g, "").replace(/\.+$/g, "").toLowerCase();
|
|
257
|
+
if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "metadata.google.internal" || hostname.endsWith(".internal")) throw new NodePreferencesError("SSRF_FORBIDDEN_PEER_URL", `Connect-time SSRF guard blocked internal host "${hostname}"`, 400);
|
|
258
|
+
if (net.isIP(hostname) !== 0) {
|
|
259
|
+
if (isPrivateOrReservedIpAddress(hostname)) throw new NodePreferencesError("SSRF_FORBIDDEN_PEER_URL", `Connect-time SSRF guard blocked private/reserved IP "${hostname}"`, 400);
|
|
260
|
+
return baseFetch(input, safeInit);
|
|
261
|
+
}
|
|
262
|
+
const resolvedAddrs = await dnsLookup(hostname);
|
|
263
|
+
if (!Array.isArray(resolvedAddrs) || resolvedAddrs.length === 0) throw new NodePreferencesError("SSRF_DNS_RESOLUTION_FAILED", `Connect-time DNS lookup returned no records for "${hostname}"`, 400);
|
|
264
|
+
for (const record of resolvedAddrs) if (!record?.address || isPrivateOrReservedIpAddress(record.address)) throw new NodePreferencesError("SSRF_FORBIDDEN_PEER_URL", `Connect-time DNS-rebinding guard blocked "${hostname}" -> "${record?.address || "unknown"}"`, 400);
|
|
265
|
+
if (parsed.protocol === "http:") {
|
|
266
|
+
const pinnedAddr = resolvedAddrs[0].address;
|
|
267
|
+
const ipHost = net.isIP(pinnedAddr) === 6 ? `[${pinnedAddr}]` : pinnedAddr;
|
|
268
|
+
const pinnedUrl = new URL(parsed.toString());
|
|
269
|
+
const originalHostHeader = parsed.host;
|
|
270
|
+
pinnedUrl.hostname = ipHost;
|
|
271
|
+
const mergedHeaders = new Headers(init?.headers);
|
|
272
|
+
if (!mergedHeaders.has("host")) mergedHeaders.set("host", originalHostHeader);
|
|
273
|
+
return baseFetch(pinnedUrl.toString(), {
|
|
274
|
+
...init,
|
|
275
|
+
headers: mergedHeaders,
|
|
276
|
+
redirect: "error"
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
return baseFetch(input, {
|
|
280
|
+
...init,
|
|
281
|
+
redirect: "error"
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Safely apply persisted `preferences.json` runtime overrides at node startup without crashing
|
|
287
|
+
* when `updateRuntimeConfig` is synchronous (`void`), while filtering role-inapplicable keys
|
|
288
|
+
* and validating Follower `peerUrls` against SSRF / DNS-rebinding rules.
|
|
289
|
+
*/
|
|
290
|
+
async function applyBootRuntimePreferences(params) {
|
|
291
|
+
const activeRuntime = params.runtime;
|
|
292
|
+
if (!activeRuntime || typeof activeRuntime.updateRuntimeConfig !== "function") return;
|
|
293
|
+
const env = params.env ?? process.env;
|
|
294
|
+
const patch = { ...params.preferencesManager.getSnapshot().runtime };
|
|
295
|
+
if (activeRuntime.role !== "follower") {
|
|
296
|
+
delete patch.peerUrls;
|
|
297
|
+
delete patch.pollIntervalMs;
|
|
298
|
+
delete patch.maxSyncLag;
|
|
299
|
+
} else if (patch.peerUrls !== void 0) try {
|
|
300
|
+
patch.peerUrls = await validateFollowerPeerUrls(patch.peerUrls, env, params.dnsLookup);
|
|
301
|
+
} catch (err) {
|
|
302
|
+
params.logger?.warn?.("[preferences] Ignoring invalid persisted follower peerUrls at boot:", err);
|
|
303
|
+
delete patch.peerUrls;
|
|
304
|
+
}
|
|
305
|
+
try {
|
|
306
|
+
await Promise.resolve(activeRuntime.updateRuntimeConfig(patch));
|
|
307
|
+
} catch (err) {
|
|
308
|
+
params.logger?.warn?.("[preferences] Failed to apply boot runtime preferences:", err);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Backward-compatible helper used by standalone chain startup (`loadPreferences(dataDir?)`).
|
|
313
|
+
* Unions immutable `CHAIN_*` env baseline with `<dataDir>/preferences.json` (when `dataDir` is passed)
|
|
314
|
+
* or `CHAIN_PREFERENCES_PATH` so an empty `preferences.json` array never wipes out env rules.
|
|
315
|
+
*/
|
|
316
|
+
function loadNodePreferences(dataDir, env = process.env) {
|
|
317
|
+
const candidatePath = (env.CHAIN_PREFERENCES_PATH || "").trim() || (typeof dataDir === "string" && dataDir.trim() ? path.join(dataDir, "preferences.json") : "");
|
|
318
|
+
let filePrefs = {};
|
|
319
|
+
if (candidatePath && fs.existsSync(candidatePath)) try {
|
|
320
|
+
const stat = fs.lstatSync(candidatePath);
|
|
321
|
+
if (!stat.isSymbolicLink() && stat.isFile()) filePrefs = JSON.parse(fs.readFileSync(candidatePath, "utf8")) || {};
|
|
322
|
+
} catch {
|
|
323
|
+
filePrefs = {};
|
|
324
|
+
}
|
|
325
|
+
const normalizeSymbolList = (items) => items.map((entry) => {
|
|
326
|
+
if (typeof entry === "string") {
|
|
327
|
+
const symbol = entry.trim().toUpperCase();
|
|
328
|
+
return symbol ? { symbol } : null;
|
|
329
|
+
}
|
|
330
|
+
if (entry && typeof entry === "object" && typeof entry.symbol === "string") {
|
|
331
|
+
const symbol = entry.symbol.trim().toUpperCase();
|
|
332
|
+
if (!symbol) return null;
|
|
333
|
+
return entry.memo ? {
|
|
334
|
+
symbol,
|
|
335
|
+
memo: String(entry.memo)
|
|
336
|
+
} : { symbol };
|
|
337
|
+
}
|
|
338
|
+
return null;
|
|
339
|
+
}).filter((x) => x !== null);
|
|
340
|
+
const normalizeBlockedList = (items) => items.map((entry) => {
|
|
341
|
+
if (typeof entry === "string") {
|
|
342
|
+
const address = entry.trim();
|
|
343
|
+
return address ? { address } : null;
|
|
344
|
+
}
|
|
345
|
+
if (entry && typeof entry === "object" && typeof entry.address === "string") {
|
|
346
|
+
const address = entry.address.trim();
|
|
347
|
+
if (!address) return null;
|
|
348
|
+
return entry.memo ? {
|
|
349
|
+
address,
|
|
350
|
+
memo: String(entry.memo)
|
|
351
|
+
} : { address };
|
|
352
|
+
}
|
|
353
|
+
return null;
|
|
354
|
+
}).filter((x) => x !== null);
|
|
355
|
+
const normalizeTrustedList = (items) => items.map((entry) => {
|
|
356
|
+
if (typeof entry === "string") {
|
|
357
|
+
const address = entry.trim();
|
|
358
|
+
return address ? { address } : null;
|
|
359
|
+
}
|
|
360
|
+
if (entry && typeof entry === "object" && typeof entry.address === "string") {
|
|
361
|
+
const address = entry.address.trim();
|
|
362
|
+
if (!address) return null;
|
|
363
|
+
const out = { address };
|
|
364
|
+
if (entry.tolerance !== void 0 && Number.isFinite(Number(entry.tolerance))) out.tolerance = Number(entry.tolerance);
|
|
365
|
+
if (entry.memo) out.memo = String(entry.memo);
|
|
366
|
+
return out;
|
|
367
|
+
}
|
|
368
|
+
return null;
|
|
369
|
+
}).filter((x) => x !== null);
|
|
370
|
+
const reservedEnv = normalizeSymbolList(parseCsvEnv(env.CHAIN_RESERVED_SYMBOLS));
|
|
371
|
+
const reservedFile = Array.isArray(filePrefs.reservedSymbols) ? normalizeSymbolList(filePrefs.reservedSymbols) : [];
|
|
372
|
+
const seenSymbols = /* @__PURE__ */ new Set();
|
|
373
|
+
const reservedSymbols = [];
|
|
374
|
+
for (const item of [...reservedEnv, ...reservedFile]) if (!seenSymbols.has(item.symbol)) {
|
|
375
|
+
seenSymbols.add(item.symbol);
|
|
376
|
+
reservedSymbols.push(item);
|
|
377
|
+
}
|
|
378
|
+
const trustedEnv = normalizeTrustedList(parseCsvEnv(env.CHAIN_TRUSTED_ACCOUNTS));
|
|
379
|
+
const trustedFile = Array.isArray(filePrefs.trustedAccounts) ? normalizeTrustedList(filePrefs.trustedAccounts) : [];
|
|
380
|
+
const seenTrusted = /* @__PURE__ */ new Set();
|
|
381
|
+
const trustedAccounts = [];
|
|
382
|
+
for (const item of [...trustedEnv, ...trustedFile]) {
|
|
383
|
+
const key = normalizeBlockedAccountKey(item.address) || item.address;
|
|
384
|
+
if (!seenTrusted.has(key)) {
|
|
385
|
+
seenTrusted.add(key);
|
|
386
|
+
trustedAccounts.push(item);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const blockedEnv = normalizeBlockedList(parseCsvEnv(env.CHAIN_BLOCKED_ACCOUNTS));
|
|
390
|
+
const blockedFile = Array.isArray(filePrefs.blockedAccounts) ? normalizeBlockedList(filePrefs.blockedAccounts) : [];
|
|
391
|
+
const seenBlocked = /* @__PURE__ */ new Set();
|
|
392
|
+
const blockedAccounts = [];
|
|
393
|
+
for (const item of [...blockedEnv, ...blockedFile]) {
|
|
394
|
+
const key = normalizeBlockedAccountKey(item.address) || item.address;
|
|
395
|
+
if (!seenBlocked.has(key)) {
|
|
396
|
+
seenBlocked.add(key);
|
|
397
|
+
blockedAccounts.push(item);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
return {
|
|
401
|
+
reservedSymbols,
|
|
402
|
+
trustedAccounts,
|
|
403
|
+
blockedAccounts
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
var NodePreferencesManager = class {
|
|
407
|
+
constructor(options = {}) {
|
|
408
|
+
this.fileState = {
|
|
409
|
+
updatedAt: null,
|
|
410
|
+
blockedAccounts: [],
|
|
411
|
+
trustedAccounts: [],
|
|
412
|
+
reservedSymbols: [],
|
|
413
|
+
runtime: {}
|
|
414
|
+
};
|
|
415
|
+
this.normalizedBlockedKeySet = /* @__PURE__ */ new Set();
|
|
416
|
+
this.normalizedReservedSymbolSet = /* @__PURE__ */ new Set();
|
|
417
|
+
this.writeChain = Promise.resolve();
|
|
418
|
+
this.env = options.env ?? process.env;
|
|
419
|
+
this.preferencesPath = (options.preferencesPath || this.env.CHAIN_PREFERENCES_PATH || "").trim() || (options.dataDir ? path.resolve(options.dataDir, "preferences.json") : null);
|
|
420
|
+
this.staticBlockedAddresses = Array.isArray(options.staticBlockedAddresses) ? options.staticBlockedAddresses.map((x) => String(x || "").trim()).filter(Boolean) : [];
|
|
421
|
+
this.baseReservedSymbols = Array.isArray(options.baseReservedSymbols) ? options.baseReservedSymbols.map((x) => String(x || "").trim().toUpperCase()).filter(Boolean) : [];
|
|
422
|
+
this.getNodeRoleFn = options.getNodeRole ?? (() => "validator");
|
|
423
|
+
this.getConsensusModeFn = options.getConsensusMode ?? (() => "single");
|
|
424
|
+
this.dnsLookup = options.dnsLookup ?? defaultDnsLookupAll;
|
|
425
|
+
this.onApplyFn = options.onApply;
|
|
426
|
+
this.reloadFromDiskSync();
|
|
427
|
+
}
|
|
428
|
+
setOnApply(fn) {
|
|
429
|
+
this.onApplyFn = fn;
|
|
430
|
+
}
|
|
431
|
+
getPreferencesPath() {
|
|
432
|
+
return this.preferencesPath;
|
|
433
|
+
}
|
|
434
|
+
reloadFromDiskSync() {
|
|
435
|
+
let parsed = {};
|
|
436
|
+
if (this.preferencesPath && fs.existsSync(this.preferencesPath)) {
|
|
437
|
+
const lstat = fs.lstatSync(this.preferencesPath);
|
|
438
|
+
if (lstat.isSymbolicLink()) throw new NodePreferencesError("SYMLINK_FORBIDDEN", "preferences.json must not be a symbolic link", 403);
|
|
439
|
+
if (lstat.isFile()) try {
|
|
440
|
+
parsed = JSON.parse(fs.readFileSync(this.preferencesPath, "utf8")) || {};
|
|
441
|
+
} catch {
|
|
442
|
+
parsed = {};
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
this.fileState = {
|
|
446
|
+
updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : null,
|
|
447
|
+
blockedAccounts: Array.isArray(parsed.blockedAccounts) ? parsed.blockedAccounts : [],
|
|
448
|
+
trustedAccounts: Array.isArray(parsed.trustedAccounts) ? parsed.trustedAccounts : [],
|
|
449
|
+
reservedSymbols: Array.isArray(parsed.reservedSymbols) ? parsed.reservedSymbols : [],
|
|
450
|
+
runtime: parsed.runtime && typeof parsed.runtime === "object" ? { ...parsed.runtime } : {}
|
|
451
|
+
};
|
|
452
|
+
this.rebuildEffectiveSnapshot();
|
|
453
|
+
return this.getSnapshot();
|
|
454
|
+
}
|
|
455
|
+
async reload() {
|
|
456
|
+
let result;
|
|
457
|
+
const task = this.writeChain.then(async () => {
|
|
458
|
+
const snap = this.reloadFromDiskSync();
|
|
459
|
+
const role = this.getNodeRoleFn();
|
|
460
|
+
const safeRuntime = { ...snap.runtime };
|
|
461
|
+
if (role !== "follower") {
|
|
462
|
+
delete safeRuntime.peerUrls;
|
|
463
|
+
delete safeRuntime.pollIntervalMs;
|
|
464
|
+
delete safeRuntime.maxSyncLag;
|
|
465
|
+
} else if (safeRuntime.peerUrls !== void 0) safeRuntime.peerUrls = await validateFollowerPeerUrls(safeRuntime.peerUrls, this.env, this.dnsLookup);
|
|
466
|
+
const safeSnap = {
|
|
467
|
+
...snap,
|
|
468
|
+
runtime: safeRuntime
|
|
469
|
+
};
|
|
470
|
+
if (this.onApplyFn) await Promise.resolve(this.onApplyFn(safeSnap, {
|
|
471
|
+
changedRuntimeKeys: Object.keys(safeRuntime),
|
|
472
|
+
requiresRestart: false
|
|
473
|
+
}));
|
|
474
|
+
result = safeSnap;
|
|
475
|
+
});
|
|
476
|
+
this.writeChain = task.catch(() => void 0);
|
|
477
|
+
await task;
|
|
478
|
+
return result;
|
|
479
|
+
}
|
|
480
|
+
getSnapshot() {
|
|
481
|
+
return {
|
|
482
|
+
preferencesPath: this.snapshotCache.preferencesPath,
|
|
483
|
+
updatedAt: this.snapshotCache.updatedAt,
|
|
484
|
+
blockedAccounts: this.snapshotCache.blockedAccounts.map((x) => ({ ...x })),
|
|
485
|
+
trustedAccounts: this.snapshotCache.trustedAccounts.map((x) => ({ ...x })),
|
|
486
|
+
reservedSymbols: this.snapshotCache.reservedSymbols.map((x) => ({ ...x })),
|
|
487
|
+
runtime: {
|
|
488
|
+
...this.snapshotCache.runtime,
|
|
489
|
+
...this.snapshotCache.runtime.peerUrls ? { peerUrls: [...this.snapshotCache.runtime.peerUrls] } : {},
|
|
490
|
+
...this.snapshotCache.runtime.healthThresholds ? { healthThresholds: { ...this.snapshotCache.runtime.healthThresholds } } : {}
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
getBlockedAddresses() {
|
|
495
|
+
return this.snapshotCache.blockedAccounts.map((entry) => entry.address);
|
|
496
|
+
}
|
|
497
|
+
getTrustedAccounts() {
|
|
498
|
+
return this.snapshotCache.trustedAccounts.map(({ address, tolerance, memo }) => ({
|
|
499
|
+
address,
|
|
500
|
+
...tolerance !== void 0 ? { tolerance } : {},
|
|
501
|
+
...memo ? { memo } : {}
|
|
502
|
+
}));
|
|
503
|
+
}
|
|
504
|
+
getEffectiveHealthThresholds() {
|
|
505
|
+
const custom = this.snapshotCache.runtime.healthThresholds;
|
|
506
|
+
return {
|
|
507
|
+
checkpointLag: Number(custom?.checkpointLag) || Number(this.env.LEDGER_HEALTH_LAG_THRESHOLD) || 1e3,
|
|
508
|
+
checkpointAgeMs: Number(custom?.checkpointAgeMs) || Number(this.env.LEDGER_HEALTH_AGE_THRESHOLD_MS) || 36e5,
|
|
509
|
+
unfinalizedAgeMs: Number(custom?.unfinalizedAgeMs) || Number(this.env.LEDGER_HEALTH_UNFINALIZED_AGE_THRESHOLD_MS) || 3e5
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
isBlocked(address) {
|
|
513
|
+
const key = normalizeBlockedAccountKey(address);
|
|
514
|
+
return Boolean(key && this.normalizedBlockedKeySet.has(key));
|
|
515
|
+
}
|
|
516
|
+
isReservedSymbol(symbol) {
|
|
517
|
+
if (typeof symbol !== "string") return false;
|
|
518
|
+
const upper = symbol.trim().toUpperCase();
|
|
519
|
+
return Boolean(upper && this.normalizedReservedSymbolSet.has(upper));
|
|
520
|
+
}
|
|
521
|
+
async update(input) {
|
|
522
|
+
const run = async () => {
|
|
523
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) throw new NodePreferencesError("INVALID_PARAMS", "Configuration payload must be a JSON object", 400);
|
|
524
|
+
const role = this.getNodeRoleFn();
|
|
525
|
+
const consensusMode = this.getConsensusModeFn();
|
|
526
|
+
const baselineBlockedKeys = new Set([...parseCsvEnv(this.env.CHAIN_BLOCKED_ACCOUNTS).map(normalizeBlockedAccountKey), ...this.staticBlockedAddresses.map(normalizeBlockedAccountKey)]);
|
|
527
|
+
const baselineTrustedKeys = new Set(parseCsvEnv(this.env.CHAIN_TRUSTED_ACCOUNTS).map(normalizeBlockedAccountKey));
|
|
528
|
+
const baselineSymbols = new Set([...this.baseReservedSymbols, ...parseCsvEnv(this.env.CHAIN_RESERVED_SYMBOLS).map((s) => s.toUpperCase())]);
|
|
529
|
+
let nextFileBlocked = this.fileState.blockedAccounts;
|
|
530
|
+
if (input.blockedAccounts !== void 0) {
|
|
531
|
+
if (!Array.isArray(input.blockedAccounts)) throw new NodePreferencesError("INVALID_PARAMS", "blockedAccounts must be an array", 400);
|
|
532
|
+
if (input.blockedAccounts.length > MAX_BLOCKED_ACCOUNTS) throw new NodePreferencesError("INVALID_PARAMS", `blockedAccounts exceeds cap of ${MAX_BLOCKED_ACCOUNTS}`, 400);
|
|
533
|
+
const dedup = /* @__PURE__ */ new Map();
|
|
534
|
+
for (const raw of input.blockedAccounts) {
|
|
535
|
+
const addr = typeof raw === "string" ? raw.trim() : typeof raw?.address === "string" ? raw.address.trim() : "";
|
|
536
|
+
if (!isValidAccountAddressCandidate(addr)) throw new NodePreferencesError("INVALID_PARAMS", `Invalid blocked account address: "${addr}"`, 400);
|
|
537
|
+
const memo = typeof raw === "object" && raw !== null ? sanitizeMemo(raw.memo) : void 0;
|
|
538
|
+
const key = normalizeBlockedAccountKey(addr);
|
|
539
|
+
if (baselineBlockedKeys.has(key)) continue;
|
|
540
|
+
if (!dedup.has(key)) dedup.set(key, memo ? {
|
|
541
|
+
address: addr,
|
|
542
|
+
memo
|
|
543
|
+
} : { address: addr });
|
|
544
|
+
}
|
|
545
|
+
nextFileBlocked = Array.from(dedup.values());
|
|
546
|
+
}
|
|
547
|
+
let nextFileTrusted = this.fileState.trustedAccounts;
|
|
548
|
+
if (input.trustedAccounts !== void 0) {
|
|
549
|
+
if (!Array.isArray(input.trustedAccounts)) throw new NodePreferencesError("INVALID_PARAMS", "trustedAccounts must be an array", 400);
|
|
550
|
+
if (input.trustedAccounts.length > MAX_TRUSTED_ACCOUNTS) throw new NodePreferencesError("INVALID_PARAMS", `trustedAccounts exceeds cap of ${MAX_TRUSTED_ACCOUNTS}`, 400);
|
|
551
|
+
const dedup = /* @__PURE__ */ new Map();
|
|
552
|
+
for (const raw of input.trustedAccounts) {
|
|
553
|
+
const addr = typeof raw === "string" ? raw.trim() : typeof raw?.address === "string" ? raw.address.trim() : "";
|
|
554
|
+
if (!isValidAccountAddressCandidate(addr)) throw new NodePreferencesError("INVALID_PARAMS", `Invalid trusted account address: "${addr}"`, 400);
|
|
555
|
+
let tolerance;
|
|
556
|
+
if (typeof raw === "object" && raw !== null && raw.tolerance !== void 0) {
|
|
557
|
+
const parsedTol = Number(raw.tolerance);
|
|
558
|
+
if (!Number.isInteger(parsedTol) || parsedTol < 0 || parsedTol > 1e9) throw new NodePreferencesError("INVALID_PARAMS", "trustedAccounts[].tolerance must be an integer between 0 and 1000000000", 400);
|
|
559
|
+
tolerance = parsedTol;
|
|
560
|
+
}
|
|
561
|
+
const memo = typeof raw === "object" && raw !== null ? sanitizeMemo(raw.memo) : void 0;
|
|
562
|
+
const key = normalizeBlockedAccountKey(addr);
|
|
563
|
+
if (baselineTrustedKeys.has(key)) continue;
|
|
564
|
+
if (!dedup.has(key)) dedup.set(key, {
|
|
565
|
+
address: addr,
|
|
566
|
+
...tolerance !== void 0 ? { tolerance } : {},
|
|
567
|
+
...memo ? { memo } : {}
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
nextFileTrusted = Array.from(dedup.values());
|
|
571
|
+
}
|
|
572
|
+
let nextFileSymbols = this.fileState.reservedSymbols;
|
|
573
|
+
const requiresRestart = false;
|
|
574
|
+
if (input.reservedSymbols !== void 0) {
|
|
575
|
+
if (!Array.isArray(input.reservedSymbols)) throw new NodePreferencesError("INVALID_PARAMS", "reservedSymbols must be an array", 400);
|
|
576
|
+
if (input.reservedSymbols.length > MAX_RESERVED_SYMBOLS) throw new NodePreferencesError("INVALID_PARAMS", `reservedSymbols exceeds cap of ${MAX_RESERVED_SYMBOLS}`, 400);
|
|
577
|
+
const dedup = /* @__PURE__ */ new Map();
|
|
578
|
+
for (const raw of input.reservedSymbols) {
|
|
579
|
+
const symRaw = typeof raw === "string" ? raw : typeof raw?.symbol === "string" ? raw.symbol : "";
|
|
580
|
+
const symbol = symRaw.trim().toUpperCase();
|
|
581
|
+
if (!/^[A-Z0-9_]{2,16}$/.test(symbol)) throw new NodePreferencesError("INVALID_PARAMS", `Invalid reserved symbol "${symRaw}" (must match /^[A-Z0-9_]{2,16}$/)`, 400);
|
|
582
|
+
const memo = typeof raw === "object" && raw !== null ? sanitizeMemo(raw.memo) : void 0;
|
|
583
|
+
if (baselineSymbols.has(symbol)) continue;
|
|
584
|
+
if (!dedup.has(symbol)) dedup.set(symbol, memo ? {
|
|
585
|
+
symbol,
|
|
586
|
+
memo
|
|
587
|
+
} : { symbol });
|
|
588
|
+
}
|
|
589
|
+
const candidateSymbols = Array.from(dedup.values());
|
|
590
|
+
if ((this.fileState.reservedSymbols || []).map((x) => typeof x === "string" ? x.toUpperCase() : x.symbol.toUpperCase()).sort().join(",") !== candidateSymbols.map((x) => x.symbol).sort().join(",")) {
|
|
591
|
+
if (role !== "validator" || consensusMode === "hotstuff") throw new NodePreferencesError("IMMUTABLE_CLUSTER_CONFIG", "reservedSymbols cannot be mutated at runtime on follower, standby, or HotStuff cluster nodes", 403);
|
|
592
|
+
}
|
|
593
|
+
nextFileSymbols = candidateSymbols;
|
|
594
|
+
}
|
|
595
|
+
const nextRuntime = { ...this.fileState.runtime };
|
|
596
|
+
const changedRuntimeKeys = [];
|
|
597
|
+
if (input.runtime !== void 0) {
|
|
598
|
+
if (input.runtime === null || typeof input.runtime !== "object" || Array.isArray(input.runtime)) throw new NodePreferencesError("INVALID_PARAMS", "runtime must be an object", 400);
|
|
599
|
+
if (input.runtime.writePolicy !== void 0) {
|
|
600
|
+
if (input.runtime.writePolicy !== "reject" && input.runtime.writePolicy !== "forward") throw new NodePreferencesError("INVALID_PARAMS", "runtime.writePolicy must be \"reject\" or \"forward\"", 400);
|
|
601
|
+
if (nextRuntime.writePolicy !== input.runtime.writePolicy) changedRuntimeKeys.push("writePolicy");
|
|
602
|
+
nextRuntime.writePolicy = input.runtime.writePolicy;
|
|
603
|
+
}
|
|
604
|
+
if (input.runtime.txMaxRequest !== void 0) {
|
|
605
|
+
const parsedMax = Number(input.runtime.txMaxRequest);
|
|
606
|
+
if (!Number.isInteger(parsedMax) || parsedMax < 1 || parsedMax > 1e4) throw new NodePreferencesError("INVALID_PARAMS", "runtime.txMaxRequest must be an integer between 1 and 10000", 400);
|
|
607
|
+
if (nextRuntime.txMaxRequest !== parsedMax) changedRuntimeKeys.push("txMaxRequest");
|
|
608
|
+
nextRuntime.txMaxRequest = parsedMax;
|
|
609
|
+
}
|
|
610
|
+
if (input.runtime.pollIntervalMs !== void 0) {
|
|
611
|
+
const parsedPoll = Number(input.runtime.pollIntervalMs);
|
|
612
|
+
if (!Number.isInteger(parsedPoll) || parsedPoll < 100 || parsedPoll > 3e5) throw new NodePreferencesError("INVALID_PARAMS", "runtime.pollIntervalMs must be an integer between 100 and 300000", 400);
|
|
613
|
+
if (nextRuntime.pollIntervalMs !== parsedPoll) changedRuntimeKeys.push("pollIntervalMs");
|
|
614
|
+
nextRuntime.pollIntervalMs = parsedPoll;
|
|
615
|
+
}
|
|
616
|
+
if (input.runtime.maxSyncLag !== void 0) {
|
|
617
|
+
const parsedLag = Number(input.runtime.maxSyncLag);
|
|
618
|
+
if (!Number.isInteger(parsedLag) || parsedLag < 0 || parsedLag > 1e6) throw new NodePreferencesError("INVALID_PARAMS", "runtime.maxSyncLag must be an integer between 0 and 1000000", 400);
|
|
619
|
+
if (nextRuntime.maxSyncLag !== parsedLag) changedRuntimeKeys.push("maxSyncLag");
|
|
620
|
+
nextRuntime.maxSyncLag = parsedLag;
|
|
621
|
+
}
|
|
622
|
+
if (input.runtime.peerUrls !== void 0) {
|
|
623
|
+
if (role === "validator") throw new NodePreferencesError("IMMUTABLE_CLUSTER_CONFIG", "Validator consensus peers cannot be mutated via runtime preferences; only follower/standby upstream peerUrls are hot-editable", 403);
|
|
624
|
+
const validatedPeers = await validateFollowerPeerUrls(input.runtime.peerUrls, this.env, this.dnsLookup);
|
|
625
|
+
if ((nextRuntime.peerUrls || []).join(",") !== validatedPeers.join(",")) changedRuntimeKeys.push("peerUrls");
|
|
626
|
+
nextRuntime.peerUrls = validatedPeers;
|
|
627
|
+
}
|
|
628
|
+
if (input.runtime.healthThresholds !== void 0) {
|
|
629
|
+
const ht = input.runtime.healthThresholds;
|
|
630
|
+
if (ht === null || typeof ht !== "object" || Array.isArray(ht)) throw new NodePreferencesError("INVALID_PARAMS", "runtime.healthThresholds must be an object", 400);
|
|
631
|
+
const nextHt = { ...nextRuntime.healthThresholds };
|
|
632
|
+
if (ht.checkpointLag !== void 0) {
|
|
633
|
+
const lag = Number(ht.checkpointLag);
|
|
634
|
+
if (!Number.isInteger(lag) || lag < 1 || lag > 1e6) throw new NodePreferencesError("INVALID_PARAMS", "healthThresholds.checkpointLag must be an integer between 1 and 1000000", 400);
|
|
635
|
+
nextHt.checkpointLag = lag;
|
|
636
|
+
}
|
|
637
|
+
if (ht.checkpointAgeMs !== void 0) {
|
|
638
|
+
const age = Number(ht.checkpointAgeMs);
|
|
639
|
+
if (!Number.isInteger(age) || age < 1e3 || age > 864e5) throw new NodePreferencesError("INVALID_PARAMS", "healthThresholds.checkpointAgeMs must be an integer between 1000 and 86400000", 400);
|
|
640
|
+
nextHt.checkpointAgeMs = age;
|
|
641
|
+
}
|
|
642
|
+
if (ht.unfinalizedAgeMs !== void 0) {
|
|
643
|
+
const unfin = Number(ht.unfinalizedAgeMs);
|
|
644
|
+
if (!Number.isInteger(unfin) || unfin < 1e3 || unfin > 864e5) throw new NodePreferencesError("INVALID_PARAMS", "healthThresholds.unfinalizedAgeMs must be an integer between 1000 and 86400000", 400);
|
|
645
|
+
nextHt.unfinalizedAgeMs = unfin;
|
|
646
|
+
}
|
|
647
|
+
nextRuntime.healthThresholds = nextHt;
|
|
648
|
+
changedRuntimeKeys.push("healthThresholds");
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
652
|
+
const persistedDoc = {
|
|
653
|
+
version: 1,
|
|
654
|
+
updatedAt: nowIso,
|
|
655
|
+
blockedAccounts: nextFileBlocked,
|
|
656
|
+
trustedAccounts: nextFileTrusted,
|
|
657
|
+
reservedSymbols: nextFileSymbols,
|
|
658
|
+
runtime: nextRuntime
|
|
659
|
+
};
|
|
660
|
+
if (this.preferencesPath) await this.atomicWritePreferencesFile(this.preferencesPath, persistedDoc);
|
|
661
|
+
this.fileState = {
|
|
662
|
+
updatedAt: nowIso,
|
|
663
|
+
blockedAccounts: nextFileBlocked,
|
|
664
|
+
trustedAccounts: nextFileTrusted,
|
|
665
|
+
reservedSymbols: nextFileSymbols,
|
|
666
|
+
runtime: nextRuntime
|
|
667
|
+
};
|
|
668
|
+
this.rebuildEffectiveSnapshot();
|
|
669
|
+
const snap = this.getSnapshot();
|
|
670
|
+
if (this.onApplyFn) await this.onApplyFn(snap, {
|
|
671
|
+
changedRuntimeKeys,
|
|
672
|
+
requiresRestart
|
|
673
|
+
});
|
|
674
|
+
return {
|
|
675
|
+
snapshot: snap,
|
|
676
|
+
requiresRestart,
|
|
677
|
+
changedRuntimeKeys
|
|
678
|
+
};
|
|
679
|
+
};
|
|
680
|
+
const next = this.writeChain.then(run, run);
|
|
681
|
+
this.writeChain = next.catch(() => void 0);
|
|
682
|
+
return next;
|
|
683
|
+
}
|
|
684
|
+
async atomicWritePreferencesFile(targetPath, payload) {
|
|
685
|
+
const parentDir = path.dirname(targetPath);
|
|
686
|
+
await fs.promises.mkdir(parentDir, { recursive: true });
|
|
687
|
+
if ((await fs.promises.lstat(parentDir)).isSymbolicLink()) throw new NodePreferencesError("SYMLINK_FORBIDDEN", "Preferences parent directory must not be a symlink", 403);
|
|
688
|
+
if (fs.existsSync(targetPath)) {
|
|
689
|
+
if ((await fs.promises.lstat(targetPath)).isSymbolicLink()) throw new NodePreferencesError("SYMLINK_FORBIDDEN", "Preferences file must not be a symbolic link", 403);
|
|
690
|
+
}
|
|
691
|
+
const tmpPath = `${targetPath}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;
|
|
692
|
+
const serialized = `${JSON.stringify(payload, null, 2)}\n`;
|
|
693
|
+
let handle = null;
|
|
694
|
+
try {
|
|
695
|
+
handle = await fs.promises.open(tmpPath, "wx", 384);
|
|
696
|
+
await handle.writeFile(serialized, "utf8");
|
|
697
|
+
await handle.sync();
|
|
698
|
+
await handle.close();
|
|
699
|
+
handle = null;
|
|
700
|
+
await fs.promises.rename(tmpPath, targetPath);
|
|
701
|
+
} catch (err) {
|
|
702
|
+
if (handle) await handle.close().catch(() => void 0);
|
|
703
|
+
await fs.promises.unlink(tmpPath).catch(() => void 0);
|
|
704
|
+
throw err;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
rebuildEffectiveSnapshot() {
|
|
708
|
+
const blockedOut = [];
|
|
709
|
+
const seenBlocked = /* @__PURE__ */ new Set();
|
|
710
|
+
for (const addr of parseCsvEnv(this.env.CHAIN_BLOCKED_ACCOUNTS)) {
|
|
711
|
+
const key = normalizeBlockedAccountKey(addr);
|
|
712
|
+
if (key && !seenBlocked.has(key)) {
|
|
713
|
+
seenBlocked.add(key);
|
|
714
|
+
blockedOut.push({
|
|
715
|
+
address: addr,
|
|
716
|
+
source: "env",
|
|
717
|
+
mutable: false
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
for (const addr of this.staticBlockedAddresses) {
|
|
722
|
+
const key = normalizeBlockedAccountKey(addr);
|
|
723
|
+
if (key && !seenBlocked.has(key)) {
|
|
724
|
+
seenBlocked.add(key);
|
|
725
|
+
blockedOut.push({
|
|
726
|
+
address: addr,
|
|
727
|
+
source: "static",
|
|
728
|
+
mutable: false
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
for (const entry of this.fileState.blockedAccounts) {
|
|
733
|
+
const addr = typeof entry === "string" ? entry.trim() : entry?.address?.trim() || "";
|
|
734
|
+
const key = normalizeBlockedAccountKey(addr);
|
|
735
|
+
if (key && !seenBlocked.has(key)) {
|
|
736
|
+
seenBlocked.add(key);
|
|
737
|
+
const memo = typeof entry === "object" && entry?.memo ? String(entry.memo) : void 0;
|
|
738
|
+
blockedOut.push({
|
|
739
|
+
address: addr,
|
|
740
|
+
...memo ? { memo } : {},
|
|
741
|
+
source: "preferences",
|
|
742
|
+
mutable: true
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
const trustedOut = [];
|
|
747
|
+
const seenTrusted = /* @__PURE__ */ new Set();
|
|
748
|
+
for (const addr of parseCsvEnv(this.env.CHAIN_TRUSTED_ACCOUNTS)) {
|
|
749
|
+
const key = normalizeBlockedAccountKey(addr);
|
|
750
|
+
if (key && !seenTrusted.has(key)) {
|
|
751
|
+
seenTrusted.add(key);
|
|
752
|
+
trustedOut.push({
|
|
753
|
+
address: addr,
|
|
754
|
+
source: "env",
|
|
755
|
+
mutable: false
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
for (const entry of this.fileState.trustedAccounts) {
|
|
760
|
+
const addr = typeof entry === "string" ? entry.trim() : entry?.address?.trim() || "";
|
|
761
|
+
const key = normalizeBlockedAccountKey(addr);
|
|
762
|
+
if (key && !seenTrusted.has(key)) {
|
|
763
|
+
seenTrusted.add(key);
|
|
764
|
+
const tolerance = typeof entry === "object" && entry?.tolerance !== void 0 && Number.isFinite(Number(entry.tolerance)) ? Number(entry.tolerance) : void 0;
|
|
765
|
+
const memo = typeof entry === "object" && entry?.memo ? String(entry.memo) : void 0;
|
|
766
|
+
trustedOut.push({
|
|
767
|
+
address: addr,
|
|
768
|
+
...tolerance !== void 0 ? { tolerance } : {},
|
|
769
|
+
...memo ? { memo } : {},
|
|
770
|
+
source: "preferences",
|
|
771
|
+
mutable: true
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
const symbolsOut = [];
|
|
776
|
+
const seenSymbols = /* @__PURE__ */ new Set();
|
|
777
|
+
for (const sym of this.baseReservedSymbols) {
|
|
778
|
+
const upper = sym.trim().toUpperCase();
|
|
779
|
+
if (upper && !seenSymbols.has(upper)) {
|
|
780
|
+
seenSymbols.add(upper);
|
|
781
|
+
symbolsOut.push({
|
|
782
|
+
symbol: upper,
|
|
783
|
+
source: "static",
|
|
784
|
+
mutable: false
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
for (const sym of parseCsvEnv(this.env.CHAIN_RESERVED_SYMBOLS)) {
|
|
789
|
+
const upper = sym.trim().toUpperCase();
|
|
790
|
+
if (upper && !seenSymbols.has(upper)) {
|
|
791
|
+
seenSymbols.add(upper);
|
|
792
|
+
symbolsOut.push({
|
|
793
|
+
symbol: upper,
|
|
794
|
+
source: "env",
|
|
795
|
+
mutable: false
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
for (const entry of this.fileState.reservedSymbols) {
|
|
800
|
+
const upper = (typeof entry === "string" ? entry : entry?.symbol || "").trim().toUpperCase();
|
|
801
|
+
if (upper && !seenSymbols.has(upper)) {
|
|
802
|
+
seenSymbols.add(upper);
|
|
803
|
+
const memo = typeof entry === "object" && entry?.memo ? String(entry.memo) : void 0;
|
|
804
|
+
symbolsOut.push({
|
|
805
|
+
symbol: upper,
|
|
806
|
+
...memo ? { memo } : {},
|
|
807
|
+
source: "preferences",
|
|
808
|
+
mutable: true
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
this.normalizedBlockedKeySet = seenBlocked;
|
|
813
|
+
this.normalizedReservedSymbolSet = seenSymbols;
|
|
814
|
+
this.snapshotCache = {
|
|
815
|
+
preferencesPath: this.preferencesPath,
|
|
816
|
+
updatedAt: this.fileState.updatedAt,
|
|
817
|
+
blockedAccounts: blockedOut,
|
|
818
|
+
trustedAccounts: trustedOut,
|
|
819
|
+
reservedSymbols: symbolsOut,
|
|
820
|
+
runtime: { ...this.fileState.runtime }
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
};
|
|
824
|
+
/**
|
|
825
|
+
* Failed-attempt bucket key. Behind cloudflared (or the Blocklet nginx) every request arrives from 127.0.0.1, so the
|
|
826
|
+
* socket address alone would put all clients in one bucket; `resolveClientIp` reads the trusted proxy header
|
|
827
|
+
* (`CHAIN_CLIENT_IP_HEADERS`, default `x-real-ip`) only from a loopback peer and ignores them from a remote one (#1922, trust rule in `@ocap/util/lib/client-ip`).
|
|
828
|
+
*/
|
|
829
|
+
function extractClientIp(req) {
|
|
830
|
+
return resolveClientIp(req) || "unknown";
|
|
831
|
+
}
|
|
832
|
+
function extractProvidedAdminToken(req) {
|
|
833
|
+
const headers = req.headers || {};
|
|
834
|
+
const authHeader = typeof headers.authorization === "string" ? headers.authorization : "";
|
|
835
|
+
const bearer = authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : "";
|
|
836
|
+
const chainAdminHeader = typeof headers["x-chain-admin-token"] === "string" ? headers["x-chain-admin-token"].trim() : "";
|
|
837
|
+
const accessKeyHeader = typeof headers["x-access-key"] === "string" ? headers["x-access-key"].trim() : "";
|
|
838
|
+
const distKeyHeader = typeof headers["x-update-token-distribution-key"] === "string" ? headers["x-update-token-distribution-key"].trim() : "";
|
|
839
|
+
const adminSpecific = chainAdminHeader || accessKeyHeader || distKeyHeader;
|
|
840
|
+
const token = bearer || adminSpecific;
|
|
841
|
+
return {
|
|
842
|
+
token,
|
|
843
|
+
hasExplicitAuthHeader: Boolean(token),
|
|
844
|
+
hasAdminSpecificHeader: Boolean(adminSpecific)
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Constant-time SHA-256 admin auth guard with bounded per-IP failed-attempt rate limiting
|
|
849
|
+
* and CSRF Content-Type / custom-header enforcement on state-mutating methods.
|
|
850
|
+
*/
|
|
851
|
+
function createAdminAuthGuard(options = {}) {
|
|
852
|
+
const env = options.env ?? process.env;
|
|
853
|
+
const windowMs = options.windowMs ?? 6e4;
|
|
854
|
+
const maxFailedAttempts = options.maxFailedAttemptsPerIp ?? 10;
|
|
855
|
+
const maxTrackedIps = options.maxTrackedIps ?? 4096;
|
|
856
|
+
const failedByIp = /* @__PURE__ */ new Map();
|
|
857
|
+
const getExpectedToken = () => String(env.CHAIN_ADMIN_TOKEN || env.CONTROL_PLANE_TOKEN || env.UPDATE_TOKEN_DISTRIBUTION_KEY || "").trim();
|
|
858
|
+
const pruneExpired = (now) => {
|
|
859
|
+
for (const [ip, entry] of failedByIp) if (entry.resetAt <= now) failedByIp.delete(ip);
|
|
860
|
+
while (failedByIp.size >= maxTrackedIps) {
|
|
861
|
+
const oldestKey = failedByIp.keys().next().value;
|
|
862
|
+
if (!oldestKey) break;
|
|
863
|
+
failedByIp.delete(oldestKey);
|
|
864
|
+
}
|
|
865
|
+
};
|
|
866
|
+
const isRateLimited = (ip, now) => {
|
|
867
|
+
const entry = failedByIp.get(ip);
|
|
868
|
+
if (!entry) return {
|
|
869
|
+
limited: false,
|
|
870
|
+
retryAfterSec: 0
|
|
871
|
+
};
|
|
872
|
+
if (entry.resetAt <= now) {
|
|
873
|
+
failedByIp.delete(ip);
|
|
874
|
+
return {
|
|
875
|
+
limited: false,
|
|
876
|
+
retryAfterSec: 0
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
if (entry.count >= maxFailedAttempts) return {
|
|
880
|
+
limited: true,
|
|
881
|
+
retryAfterSec: Math.max(1, Math.ceil((entry.resetAt - now) / 1e3))
|
|
882
|
+
};
|
|
883
|
+
return {
|
|
884
|
+
limited: false,
|
|
885
|
+
retryAfterSec: 0
|
|
886
|
+
};
|
|
887
|
+
};
|
|
888
|
+
const recordFailure = (ip, now) => {
|
|
889
|
+
const existing = failedByIp.get(ip);
|
|
890
|
+
if (!existing || existing.resetAt <= now) {
|
|
891
|
+
if (failedByIp.size >= maxTrackedIps) pruneExpired(now);
|
|
892
|
+
failedByIp.set(ip, {
|
|
893
|
+
count: 1,
|
|
894
|
+
resetAt: now + windowMs
|
|
895
|
+
});
|
|
896
|
+
} else if (existing.count < maxFailedAttempts) existing.count += 1;
|
|
897
|
+
};
|
|
898
|
+
const hasGatewayOwnerOrAdminRole = (req) => {
|
|
899
|
+
const user = req.user;
|
|
900
|
+
return Boolean(user && typeof user.role === "string" && (user.role === "owner" || user.role === "admin"));
|
|
901
|
+
};
|
|
902
|
+
const isSameOriginSessionMutation = (req) => {
|
|
903
|
+
const originHeader = typeof req.headers?.origin === "string" ? req.headers.origin.trim() : "";
|
|
904
|
+
if (!originHeader) return true;
|
|
905
|
+
const rawHost = (Boolean(req.app?.get?.("trust proxy")) && typeof req.headers?.["x-forwarded-host"] === "string" ? req.headers["x-forwarded-host"].split(",")[0].trim() : "") || (typeof req.headers?.host === "string" ? req.headers.host.trim() : "");
|
|
906
|
+
if (!rawHost) return false;
|
|
907
|
+
try {
|
|
908
|
+
return new URL(originHeader).host.toLowerCase() === rawHost.toLowerCase();
|
|
909
|
+
} catch {
|
|
910
|
+
return false;
|
|
911
|
+
}
|
|
912
|
+
};
|
|
913
|
+
const isAuthenticatedRequest = (req) => {
|
|
914
|
+
if (hasGatewayOwnerOrAdminRole(req)) return true;
|
|
915
|
+
const expected = getExpectedToken();
|
|
916
|
+
const { token, hasExplicitAuthHeader, hasAdminSpecificHeader } = extractProvidedAdminToken(req);
|
|
917
|
+
if (!expected || !token) return false;
|
|
918
|
+
if (timingSafeTokenEqual(expected, token)) return true;
|
|
919
|
+
const isGatewayNonAdminBearerOnly = Boolean(req.user) && !hasAdminSpecificHeader;
|
|
920
|
+
if (hasExplicitAuthHeader && !isGatewayNonAdminBearerOnly) {
|
|
921
|
+
const now = Date.now();
|
|
922
|
+
const ip = extractClientIp(req);
|
|
923
|
+
if (!isRateLimited(ip, now).limited) recordFailure(ip, now);
|
|
924
|
+
}
|
|
925
|
+
return false;
|
|
926
|
+
};
|
|
927
|
+
const checkOptionalAdmin = (req, res) => {
|
|
928
|
+
if (hasGatewayOwnerOrAdminRole(req)) return "admin";
|
|
929
|
+
const { token, hasExplicitAuthHeader, hasAdminSpecificHeader } = extractProvidedAdminToken(req);
|
|
930
|
+
if (!hasExplicitAuthHeader || !token) return "anonymous";
|
|
931
|
+
const expected = getExpectedToken();
|
|
932
|
+
if (!expected) return "anonymous";
|
|
933
|
+
if (timingSafeTokenEqual(expected, token)) return "admin";
|
|
934
|
+
if (Boolean(req.user) && !hasAdminSpecificHeader) return "anonymous";
|
|
935
|
+
const now = Date.now();
|
|
936
|
+
const ip = extractClientIp(req);
|
|
937
|
+
const rate = isRateLimited(ip, now);
|
|
938
|
+
if (rate.limited) {
|
|
939
|
+
res.setHeader("Retry-After", String(rate.retryAfterSec));
|
|
940
|
+
res.status(429).json({
|
|
941
|
+
code: "AUTH_RATE_LIMITED",
|
|
942
|
+
error: "Too many failed authentication attempts; retry later"
|
|
943
|
+
});
|
|
944
|
+
return "rate_limited";
|
|
945
|
+
}
|
|
946
|
+
recordFailure(ip, now);
|
|
947
|
+
return "anonymous";
|
|
948
|
+
};
|
|
949
|
+
const requireAdmin = (req, res, next) => {
|
|
950
|
+
const method = String(req.method || "GET").toUpperCase();
|
|
951
|
+
const isMutating = method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";
|
|
952
|
+
if (isMutating) {
|
|
953
|
+
const contentType = String(req.headers?.["content-type"] || "").trim().toLowerCase();
|
|
954
|
+
if (contentType && (contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("multipart/form-data") || contentType.startsWith("text/plain"))) {
|
|
955
|
+
res.status(415).json({
|
|
956
|
+
code: "UNSUPPORTED_MEDIA_TYPE",
|
|
957
|
+
error: "Mutating admin endpoints require Content-Type: application/json"
|
|
958
|
+
});
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
if (hasGatewayOwnerOrAdminRole(req)) {
|
|
963
|
+
if (isMutating) {
|
|
964
|
+
if (!isSameOriginSessionMutation(req)) {
|
|
965
|
+
res.status(403).json({
|
|
966
|
+
code: "CSRF_ORIGIN_MISMATCH",
|
|
967
|
+
error: "Cross-origin state-changing session request blocked"
|
|
968
|
+
});
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
if (!(Boolean(req.headers?.["x-requested-with"]) || Boolean(req.headers?.["x-chain-admin-token"]) || String(req.headers?.["content-type"] || "").toLowerCase().includes("application/json"))) {
|
|
972
|
+
res.status(403).json({
|
|
973
|
+
code: "CSRF_HEADER_REQUIRED",
|
|
974
|
+
error: "State-changing requests with session auth must send Content-Type: application/json or X-Requested-With"
|
|
975
|
+
});
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
next();
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
const expected = getExpectedToken();
|
|
983
|
+
if (!expected) {
|
|
984
|
+
res.status(401).json({
|
|
985
|
+
code: "ADMIN_TOKEN_NOT_CONFIGURED",
|
|
986
|
+
error: "unauthorized: admin token not configured"
|
|
987
|
+
});
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
const { token } = extractProvidedAdminToken(req);
|
|
991
|
+
if (token && timingSafeTokenEqual(expected, token)) {
|
|
992
|
+
next();
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
const now = Date.now();
|
|
996
|
+
const ip = extractClientIp(req);
|
|
997
|
+
const rate = isRateLimited(ip, now);
|
|
998
|
+
if (rate.limited) {
|
|
999
|
+
res.setHeader("Retry-After", String(rate.retryAfterSec));
|
|
1000
|
+
res.status(429).json({
|
|
1001
|
+
code: "AUTH_RATE_LIMITED",
|
|
1002
|
+
error: "Too many failed authentication attempts; retry later"
|
|
1003
|
+
});
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
recordFailure(ip, now);
|
|
1007
|
+
res.status(403).json({
|
|
1008
|
+
code: "FORBIDDEN",
|
|
1009
|
+
error: "forbidden"
|
|
1010
|
+
});
|
|
1011
|
+
};
|
|
1012
|
+
return {
|
|
1013
|
+
isConfigured: () => Boolean(getExpectedToken()),
|
|
1014
|
+
isAuthenticatedRequest,
|
|
1015
|
+
checkOptionalAdmin,
|
|
1016
|
+
requireAdmin
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
//#endregion
|
|
1021
|
+
export { MAX_BLOCKED_ACCOUNTS, MAX_CONFIG_BODY_BYTES, MAX_MEMO_LENGTH, MAX_PEER_URLS, MAX_RESERVED_SYMBOLS, MAX_TRUSTED_ACCOUNTS, NodePreferencesError, NodePreferencesManager, applyBootRuntimePreferences, createAdminAuthGuard, createFollowerPeerFetchGuard, isPrivateOrReservedIpAddress, isValidAccountAddressCandidate, loadNodePreferences, normalizeBlockedAccountKey, timingSafeTokenEqual, validateFollowerPeerUrls };
|