@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.
- package/esm/access-log.d.mts +5 -2
- package/esm/access-log.mjs +5 -3
- package/esm/config-consistency.mjs +38 -2
- package/esm/did-tls.d.mts +192 -0
- package/esm/did-tls.mjs +1606 -0
- package/esm/env.d.mts +17 -2
- package/esm/env.mjs +126 -1
- package/esm/follower-config.d.mts +3 -2
- package/esm/follower-config.mjs +30 -4
- package/esm/index.d.mts +6 -4
- package/esm/index.mjs +5 -3
- package/esm/mesh-egress.d.mts +30 -0
- package/esm/mesh-egress.mjs +152 -0
- package/esm/start-chain-node.d.mts +6 -1
- package/esm/start-chain-node.mjs +822 -49
- package/esm/types.d.mts +68 -2
- package/lib/access-log.cjs +4 -2
- package/lib/access-log.d.cts +5 -2
- package/lib/config-consistency.cjs +38 -2
- package/lib/did-tls.cjs +1628 -0
- package/lib/did-tls.d.cts +192 -0
- package/lib/env.cjs +131 -1
- package/lib/env.d.cts +17 -2
- package/lib/follower-config.cjs +30 -3
- package/lib/follower-config.d.cts +3 -2
- package/lib/index.cjs +30 -1
- package/lib/index.d.cts +6 -4
- package/lib/mesh-egress.cjs +155 -0
- package/lib/mesh-egress.d.cts +30 -0
- package/lib/start-chain-node.cjs +824 -48
- package/lib/start-chain-node.d.cts +6 -1
- package/lib/types.d.cts +67 -1
- package/package.json +16 -16
package/esm/env.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ChainNodeRoleConfig, ILedgerLeaseOptions, RunningChainNode, ValidatorSignerConfig } from "./types.mjs";
|
|
1
|
+
import { ChainHttpTlsConfig, ChainNodeRoleConfig, ILedgerLeaseOptions, RunningChainNode, ValidatorSignerConfig } from "./types.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/env.d.ts
|
|
4
4
|
|
|
@@ -16,6 +16,21 @@ declare function roleConfigFromEnv(env: Record<string, string | undefined>, opti
|
|
|
16
16
|
* Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
|
|
17
17
|
*/
|
|
18
18
|
declare function leaseConfigFromEnv(env: Record<string, string | undefined>): ILedgerLeaseOptions | false;
|
|
19
|
+
/**
|
|
20
|
+
* Walk every existing path component from filesystem root down to `resolvedPath` via `lstatSync`
|
|
21
|
+
* and refuse any symlinked directory or leaf (exempting only macOS depth-1 OS symlinks `/var`, `/tmp`, `/etc`).
|
|
22
|
+
*/
|
|
23
|
+
declare function assertNoSymlinkAncestors(resolvedPath: string, label: string): void;
|
|
24
|
+
/**
|
|
25
|
+
* Pure environment-to-`ARC_MESH_EGRESS_URL` parser (`@ocap/chain-node`, #2025).
|
|
26
|
+
* Reads ONLY the explicitly supplied `env` dictionary.
|
|
27
|
+
*/
|
|
28
|
+
declare function meshEgressUrlFromEnv(env: Record<string, string | undefined>): string | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Pure environment-to-DID-TLS/mTLS listener parser (`@ocap/chain-node`, #2025).
|
|
31
|
+
* Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
|
|
32
|
+
*/
|
|
33
|
+
declare function tlsConfigFromEnv(env: Record<string, string | undefined>): ChainHttpTlsConfig | undefined;
|
|
19
34
|
interface InstallProcessSignalHandlersOptions {
|
|
20
35
|
timeoutMs?: number;
|
|
21
36
|
signals?: NodeJS.Signals[];
|
|
@@ -29,4 +44,4 @@ interface InstallProcessSignalHandlersOptions {
|
|
|
29
44
|
*/
|
|
30
45
|
declare function installProcessSignalHandlers(node: Pick<RunningChainNode, 'stop'>, options?: InstallProcessSignalHandlersOptions): () => void;
|
|
31
46
|
//#endregion
|
|
32
|
-
export { InstallProcessSignalHandlersOptions, installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv };
|
|
47
|
+
export { InstallProcessSignalHandlersOptions, assertNoSymlinkAncestors, installProcessSignalHandlers, leaseConfigFromEnv, meshEgressUrlFromEnv, roleConfigFromEnv, tlsConfigFromEnv };
|
package/esm/env.mjs
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
+
import { canonicalizeTlsDid, decodeEd25519PublicKeyPin } from "./did-tls.mjs";
|
|
2
|
+
import { parseMeshEgressUrl } from "./mesh-egress.mjs";
|
|
1
3
|
import { CustomError } from "@ocap/util/lib/error";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
2
6
|
import { normalizeDidForCompare, resolveConsensusProposer, resolveConsensusProposerFromSigner, resolveEnvWitnessWallet, resolveNodeRoleConfig } from "@arcblock/ledger-core";
|
|
3
7
|
import { resolveLedgerLeaseConfig } from "@arcblock/ledger-sqlite";
|
|
4
8
|
|
|
@@ -82,6 +86,7 @@ function roleConfigFromEnv(env, options) {
|
|
|
82
86
|
if (!env || typeof env !== "object") throw new CustomError("INVALID_CONFIG", "roleConfigFromEnv requires an explicit env record");
|
|
83
87
|
const resolved = resolveNodeRoleConfig(env);
|
|
84
88
|
const allowPrivatePeers = parseBoolEnv(env.ALLOW_PRIVATE_PEER_URLS);
|
|
89
|
+
const meshEgress = parseMeshEgressUrl(env.ARC_MESH_EGRESS_URL, "ARC_MESH_EGRESS_URL");
|
|
85
90
|
const explicitOrEnvSigner = resolveSignerFromEnvRecord(env, options?.signer);
|
|
86
91
|
if (resolved.role === "validator") {
|
|
87
92
|
if (!explicitOrEnvSigner) throw new CustomError("INVALID_CONFIG", "Validator role requires options.signer or explicit CHAIN_CONSENSUS_SK + CHAIN_CONSENSUS_PROPOSER in env");
|
|
@@ -98,6 +103,7 @@ function roleConfigFromEnv(env, options) {
|
|
|
98
103
|
allowPublicConsensusBind: resolved.allowPublicConsensusBind,
|
|
99
104
|
writePolicy: resolved.writePolicy,
|
|
100
105
|
allowPrivatePeers,
|
|
106
|
+
...meshEgress ? { meshEgressUrl: meshEgress.normalizedUrl } : {},
|
|
101
107
|
retentionMode: resolved.retentionMode,
|
|
102
108
|
hotWindowEntries: resolved.hotWindowEntries,
|
|
103
109
|
hotWindowCheckpoints: resolved.hotWindowCheckpoints,
|
|
@@ -134,11 +140,16 @@ function roleConfigFromEnv(env, options) {
|
|
|
134
140
|
clusterPeerUrls: resolved.clusterPeerUrls,
|
|
135
141
|
snapshotBaseUrl: resolved.snapshotBaseUrl,
|
|
136
142
|
...snapshotPrefix ? { snapshotPrefix } : {},
|
|
143
|
+
...resolved.bootstrapSource ? { bootstrapSource: resolved.bootstrapSource } : {},
|
|
144
|
+
...resolved.da ? { da: resolved.da } : {},
|
|
145
|
+
...resolved.daCrossCheck ? { daCrossCheck: resolved.daCrossCheck } : {},
|
|
146
|
+
...resolved.daCrossCheckIncomplete ? { daCrossCheckIncomplete: resolved.daCrossCheckIncomplete } : {},
|
|
137
147
|
trustedProposer: resolved.trustedProposer,
|
|
138
148
|
trustedProposerPublicKey: resolved.trustedProposerPublicKey,
|
|
139
149
|
...resolved.hotstuffValidators.length > 0 ? { hotstuffValidators: resolved.hotstuffValidators } : {},
|
|
140
150
|
...resolved.hotstuffQuorumThreshold !== void 0 ? { hotstuffQuorumThreshold: resolved.hotstuffQuorumThreshold } : {},
|
|
141
151
|
allowPrivatePeers,
|
|
152
|
+
...meshEgress ? { meshEgressUrl: meshEgress.normalizedUrl } : {},
|
|
142
153
|
disallowKeylessCascadedUpstream,
|
|
143
154
|
allowUnauthenticatedBootstrap: resolved.allowUnauthenticatedBootstrap,
|
|
144
155
|
syncMode: resolved.syncMode,
|
|
@@ -170,6 +181,120 @@ function leaseConfigFromEnv(env) {
|
|
|
170
181
|
startupWaitMs: parsed.startupWaitMs
|
|
171
182
|
};
|
|
172
183
|
}
|
|
184
|
+
function parseOptionalStrictBool(raw, label) {
|
|
185
|
+
const norm = (raw ?? "").trim().toLowerCase();
|
|
186
|
+
if (!norm) return void 0;
|
|
187
|
+
if (norm === "1" || norm === "true") return true;
|
|
188
|
+
if (norm === "0" || norm === "false") return false;
|
|
189
|
+
throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected 1/true or 0/false`);
|
|
190
|
+
}
|
|
191
|
+
function parseCsvEnvList(raw) {
|
|
192
|
+
if (!raw) return [];
|
|
193
|
+
return raw.split(",").map((s) => s.trim()).filter(Boolean);
|
|
194
|
+
}
|
|
195
|
+
const DARWIN_OS_ROOT_SYMLINKS = new Set([
|
|
196
|
+
"/var",
|
|
197
|
+
"/tmp",
|
|
198
|
+
"/etc"
|
|
199
|
+
]);
|
|
200
|
+
/**
|
|
201
|
+
* Walk every existing path component from filesystem root down to `resolvedPath` via `lstatSync`
|
|
202
|
+
* and refuse any symlinked directory or leaf (exempting only macOS depth-1 OS symlinks `/var`, `/tmp`, `/etc`).
|
|
203
|
+
*/
|
|
204
|
+
function assertNoSymlinkAncestors(resolvedPath, label) {
|
|
205
|
+
const parsed = path.parse(resolvedPath);
|
|
206
|
+
const parts = resolvedPath.slice(parsed.root.length).split(path.sep).filter(Boolean);
|
|
207
|
+
let cur = parsed.root;
|
|
208
|
+
for (let i = 0; i < parts.length; i++) {
|
|
209
|
+
cur = path.join(cur, parts[i]);
|
|
210
|
+
let st;
|
|
211
|
+
try {
|
|
212
|
+
st = fs.lstatSync(cur);
|
|
213
|
+
} catch (err) {
|
|
214
|
+
if (err?.code === "ENOENT") break;
|
|
215
|
+
throw new CustomError("INVALID_CONFIG", `Cannot stat path component for ${label} (${cur}): ${err?.code || "EIO"}`);
|
|
216
|
+
}
|
|
217
|
+
if (st.isSymbolicLink()) {
|
|
218
|
+
if (process.platform === "darwin" && i === 0 && DARWIN_OS_ROOT_SYMLINKS.has(cur)) continue;
|
|
219
|
+
throw new CustomError("SECURITY_VIOLATION", `Refusing symlinked path component in ${label}: ${cur}`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function assertNonSymlinkRegularFilePath(rawPath, label) {
|
|
224
|
+
const resolved = path.resolve(rawPath.trim());
|
|
225
|
+
assertNoSymlinkAncestors(resolved, label);
|
|
226
|
+
let stat;
|
|
227
|
+
try {
|
|
228
|
+
stat = fs.lstatSync(resolved);
|
|
229
|
+
} catch (err) {
|
|
230
|
+
throw new CustomError("INVALID_CONFIG", `${label} file does not exist or cannot be stat'd (${resolved}): ${err?.code || "ENOENT"}`);
|
|
231
|
+
}
|
|
232
|
+
if (stat.isSymbolicLink()) throw new CustomError("SECURITY_VIOLATION", `Refusing symlinked ${label} file: ${resolved}`);
|
|
233
|
+
if (!stat.isFile()) throw new CustomError("INVALID_CONFIG", `${label} must point to a regular file: ${resolved}`);
|
|
234
|
+
return resolved;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Pure environment-to-`ARC_MESH_EGRESS_URL` parser (`@ocap/chain-node`, #2025).
|
|
238
|
+
* Reads ONLY the explicitly supplied `env` dictionary.
|
|
239
|
+
*/
|
|
240
|
+
function meshEgressUrlFromEnv(env) {
|
|
241
|
+
if (!env || typeof env !== "object") throw new CustomError("INVALID_CONFIG", "meshEgressUrlFromEnv requires an explicit env record");
|
|
242
|
+
return parseMeshEgressUrl(env.ARC_MESH_EGRESS_URL, "ARC_MESH_EGRESS_URL")?.normalizedUrl;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Pure environment-to-DID-TLS/mTLS listener parser (`@ocap/chain-node`, #2025).
|
|
246
|
+
* Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
|
|
247
|
+
*/
|
|
248
|
+
function tlsConfigFromEnv(env) {
|
|
249
|
+
if (!env || typeof env !== "object") throw new CustomError("INVALID_CONFIG", "tlsConfigFromEnv requires an explicit env record");
|
|
250
|
+
const enabled = parseOptionalStrictBool(env.RPC_TLS_ENABLED, "RPC_TLS_ENABLED");
|
|
251
|
+
if (!enabled) return enabled === false ? { enabled: false } : void 0;
|
|
252
|
+
const rawWire = (env.RPC_TLS_WIRE_ALGORITHM ?? "").trim().toLowerCase();
|
|
253
|
+
let wireAlgorithm = "p256";
|
|
254
|
+
if (rawWire) {
|
|
255
|
+
if (rawWire !== "ed25519" && rawWire !== "p256") throw new CustomError("INVALID_CONFIG", `Unsupported RPC_TLS_WIRE_ALGORITHM="${env.RPC_TLS_WIRE_ALGORITHM}": expected ed25519 or p256`);
|
|
256
|
+
wireAlgorithm = rawWire;
|
|
257
|
+
}
|
|
258
|
+
const requireClientCert = parseOptionalStrictBool(env.RPC_TLS_REQUIRE_CLIENT_CERT, "RPC_TLS_REQUIRE_CLIENT_CERT") ?? true;
|
|
259
|
+
const rawIssuerPins = parseCsvEnvList(env.RPC_TLS_ALLOWED_ISSUER_PKS);
|
|
260
|
+
for (const item of rawIssuerPins) try {
|
|
261
|
+
if (item.includes("=")) {
|
|
262
|
+
const eq = item.indexOf("=");
|
|
263
|
+
canonicalizeTlsDid(item.slice(0, eq), "RPC_TLS_ALLOWED_ISSUER_PKS DID");
|
|
264
|
+
decodeEd25519PublicKeyPin(item.slice(eq + 1), "RPC_TLS_ALLOWED_ISSUER_PKS pubkey");
|
|
265
|
+
} else decodeEd25519PublicKeyPin(item, "RPC_TLS_ALLOWED_ISSUER_PKS pubkey");
|
|
266
|
+
} catch (err) {
|
|
267
|
+
throw new CustomError("INVALID_CONFIG", `Invalid entry in RPC_TLS_ALLOWED_ISSUER_PKS: ${err instanceof Error ? err.message : String(err)}`);
|
|
268
|
+
}
|
|
269
|
+
if (requireClientCert && rawIssuerPins.length === 0) throw new CustomError("INVALID_CONFIG", "RPC_TLS_ENABLED=1 with RPC_TLS_REQUIRE_CLIENT_CERT=true requires at least one pinned Ed25519 key in RPC_TLS_ALLOWED_ISSUER_PKS");
|
|
270
|
+
const rawClientDids = parseCsvEnvList(env.RPC_TLS_ALLOWED_CLIENT_DIDS);
|
|
271
|
+
const allowedClientDids = [];
|
|
272
|
+
for (const did of rawClientDids) try {
|
|
273
|
+
allowedClientDids.push(canonicalizeTlsDid(did, "RPC_TLS_ALLOWED_CLIENT_DIDS"));
|
|
274
|
+
} catch (err) {
|
|
275
|
+
throw new CustomError("INVALID_CONFIG", `Invalid DID in RPC_TLS_ALLOWED_CLIENT_DIDS: ${err instanceof Error ? err.message : String(err)}`);
|
|
276
|
+
}
|
|
277
|
+
const sanDnsNames = parseCsvEnvList(env.RPC_TLS_SAN_DNS);
|
|
278
|
+
const sanIpAddresses = parseCsvEnvList(env.RPC_TLS_SAN_IPS);
|
|
279
|
+
const rawCertFile = (env.RPC_TLS_CERT_FILE ?? "").trim();
|
|
280
|
+
const rawKeyFile = (env.RPC_TLS_KEY_FILE ?? "").trim();
|
|
281
|
+
if (Boolean(rawCertFile) !== Boolean(rawKeyFile)) throw new CustomError("INVALID_CONFIG", "RPC_TLS_CERT_FILE and RPC_TLS_KEY_FILE must both be set together when overriding DID-TLS credentials");
|
|
282
|
+
const certFile = rawCertFile ? assertNonSymlinkRegularFilePath(rawCertFile, "RPC_TLS_CERT_FILE") : void 0;
|
|
283
|
+
const keyFile = rawKeyFile ? assertNonSymlinkRegularFilePath(rawKeyFile, "RPC_TLS_KEY_FILE") : void 0;
|
|
284
|
+
const chainSk = (env.CHAIN_SK ?? "").trim() || void 0;
|
|
285
|
+
return {
|
|
286
|
+
enabled: true,
|
|
287
|
+
wireAlgorithm,
|
|
288
|
+
requireClientCert,
|
|
289
|
+
allowedIssuerPublicKeys: rawIssuerPins,
|
|
290
|
+
...allowedClientDids.length > 0 ? { allowedClientDids } : {},
|
|
291
|
+
...sanDnsNames.length > 0 ? { sanDnsNames } : {},
|
|
292
|
+
...sanIpAddresses.length > 0 ? { sanIpAddresses } : {},
|
|
293
|
+
...certFile ? { certFile } : {},
|
|
294
|
+
...keyFile ? { keyFile } : {},
|
|
295
|
+
...chainSk ? { identitySecretKey: chainSk } : {}
|
|
296
|
+
};
|
|
297
|
+
}
|
|
173
298
|
/**
|
|
174
299
|
* Install idempotent `SIGTERM` / `SIGINT` graceful shutdown handlers for a running chain node.
|
|
175
300
|
* Returns a cleanup callback that removes the signal listeners.
|
|
@@ -215,4 +340,4 @@ function installProcessSignalHandlers(node, options) {
|
|
|
215
340
|
}
|
|
216
341
|
|
|
217
342
|
//#endregion
|
|
218
|
-
export { installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv };
|
|
343
|
+
export { assertNoSymlinkAncestors, installProcessSignalHandlers, leaseConfigFromEnv, meshEgressUrlFromEnv, roleConfigFromEnv, tlsConfigFromEnv };
|
|
@@ -15,11 +15,12 @@ declare function mergeTransactionOverlay(base: unknown, overlay: unknown): unkno
|
|
|
15
15
|
* variables from env (e.g. CHAIN_TX_BRIDGE_ENABLED): the stored row is not rewritten on a ledger-anchored leader
|
|
16
16
|
* restart, so it still holds the values of the last genesis/config write.
|
|
17
17
|
*/
|
|
18
|
-
declare function rehydrateFollowerChainConfig(storedChain: unknown, profileChainConfig?: Partial<IChainConfig
|
|
18
|
+
declare function rehydrateFollowerChainConfig(storedChain: unknown, profileChainConfig?: Partial<IChainConfig>, extraReservedSymbols?: readonly string[]): IChainConfig;
|
|
19
19
|
/**
|
|
20
20
|
* The config a resolver actually runs with (`OCAPResolver` constructor): validated, with `token.address` set to the
|
|
21
21
|
* genesis token address. This is what the leader's `getConfig` returns and what the follower's replayer reads.
|
|
22
22
|
*/
|
|
23
23
|
declare function toResolverConfig(config: IChainConfig): IChainConfig;
|
|
24
|
+
declare function orphanIndexFromSequence(chainId: string, override?: number): number;
|
|
24
25
|
//#endregion
|
|
25
|
-
export { isCompleteChainConfig, isPlainRecord, mergeTransactionOverlay, rehydrateFollowerChainConfig, toResolverConfig };
|
|
26
|
+
export { isCompleteChainConfig, isPlainRecord, mergeTransactionOverlay, orphanIndexFromSequence, rehydrateFollowerChainConfig, toResolverConfig };
|
package/esm/follower-config.mjs
CHANGED
|
@@ -29,16 +29,24 @@ function mergeTransactionOverlay(base, overlay) {
|
|
|
29
29
|
* variables from env (e.g. CHAIN_TX_BRIDGE_ENABLED): the stored row is not rewritten on a ledger-anchored leader
|
|
30
30
|
* restart, so it still holds the values of the last genesis/config write.
|
|
31
31
|
*/
|
|
32
|
-
function rehydrateFollowerChainConfig(storedChain, profileChainConfig) {
|
|
32
|
+
function rehydrateFollowerChainConfig(storedChain, profileChainConfig, extraReservedSymbols) {
|
|
33
33
|
const storedChainPartial = storedChain;
|
|
34
34
|
const storedChainId = typeof storedChainPartial.chainId === "string" ? storedChainPartial.chainId.trim() : "";
|
|
35
35
|
const baseSymbol = storedChainPartial.token?.symbol || "TBA";
|
|
36
|
-
const reservedSymbols = Array.from(new Set([
|
|
36
|
+
const reservedSymbols = Array.from(new Set([
|
|
37
|
+
baseSymbol,
|
|
38
|
+
...storedChainPartial.reservedSymbols ?? [],
|
|
39
|
+
...profileChainConfig?.reservedSymbols ?? [],
|
|
40
|
+
...extraReservedSymbols ?? []
|
|
41
|
+
].map((s) => String(s || "").trim().toUpperCase()).filter(Boolean)));
|
|
37
42
|
const transactionOverlay = isPlainRecord(profileChainConfig?.transaction) ? profileChainConfig.transaction : void 0;
|
|
43
|
+
const storedTransaction = isPlainRecord(storedChainPartial.transaction) ? { ...storedChainPartial.transaction } : storedChainPartial.transaction;
|
|
44
|
+
if (isPlainRecord(storedTransaction)) delete storedTransaction.maxTxSize;
|
|
45
|
+
const transaction = transactionOverlay ? mergeTransactionOverlay(storedTransaction, transactionOverlay) : storedTransaction;
|
|
38
46
|
return Config.create({
|
|
39
47
|
...storedChain,
|
|
40
48
|
...storedChainId ? { chainId: storedChainId } : {},
|
|
41
|
-
...
|
|
49
|
+
...transaction !== void 0 ? { transaction } : {},
|
|
42
50
|
reservedSymbols
|
|
43
51
|
});
|
|
44
52
|
}
|
|
@@ -52,6 +60,24 @@ function toResolverConfig(config) {
|
|
|
52
60
|
if (tokenItx) validated.token.address = tokenItx.address;
|
|
53
61
|
return validated;
|
|
54
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* First ledger sequence whose orphan entries (finalized, no stateCommitHash, no statedb tx row) the chain's leader
|
|
65
|
+
* indexed. Leaders index the orphans they produce since 1.31.1 (#1387); before that they never did, and a follower
|
|
66
|
+
* index must hold exactly what the leader's holds (#1875). Values read from the leaders' indexdb: the first orphan
|
|
67
|
+
* with an index row, every earlier one without (beta: last unindexed 437972; main: last unindexed 832519). A chain
|
|
68
|
+
* started on 1.31.1+ indexed all of them.
|
|
69
|
+
*/
|
|
70
|
+
const ORPHAN_INDEX_FROM_SEQUENCE = Object.freeze({
|
|
71
|
+
beta: 437983,
|
|
72
|
+
"xenon-2020-01-15": 832598
|
|
73
|
+
});
|
|
74
|
+
function orphanIndexFromSequence(chainId, override) {
|
|
75
|
+
if (override !== void 0) {
|
|
76
|
+
if (!Number.isSafeInteger(override) || override < 1) throw new Error(`orphanIndexFromSequence must be a positive integer, got ${String(override)}`);
|
|
77
|
+
return override;
|
|
78
|
+
}
|
|
79
|
+
return Object.hasOwn(ORPHAN_INDEX_FROM_SEQUENCE, chainId) ? ORPHAN_INDEX_FROM_SEQUENCE[chainId] ?? 1 : 1;
|
|
80
|
+
}
|
|
55
81
|
|
|
56
82
|
//#endregion
|
|
57
|
-
export { isCompleteChainConfig, isPlainRecord, mergeTransactionOverlay, rehydrateFollowerChainConfig, toResolverConfig };
|
|
83
|
+
export { isCompleteChainConfig, isPlainRecord, mergeTransactionOverlay, orphanIndexFromSequence, rehydrateFollowerChainConfig, toResolverConfig };
|
package/esm/index.d.mts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { BLOCKLET_ENV_CHAIN_FALLBACKS, BlockletEnvLeftovers, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, FutureTimestampGuardConfig, STANDALONE_ENV_MARKERS, TChainConfigCheckMode, TRANSACTION_SWITCH_ENV, TransactionSwitches, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, parseNonNegativeNumberEnv, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject } from "./standalone-env.mjs";
|
|
2
2
|
import { CONSENSUS_CONFIG_KEYS, ConfigDifference, VerifyFollowerConfigOptions, VerifyFollowerConfigResult, diffConsensusConfig, fetchUpstreamChainConfig, formatConfigDifferences, normalizeConsensusConfig, verifyFollowerConfigAgainstUpstream } from "./config-consistency.mjs";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { DEFAULT_DID_TLS_CLOCK_SKEW_SECONDS, DID_TLS_BINDING_DOMAIN, DID_TLS_BINDING_PROOF_OID, DID_TLS_P256_HKDF_INFO_PREFIX, DID_TLS_P256_HKDF_SALT, DidTlsAllowedIssuerPinsInput, DidTlsEndpointRole, DidTlsKeyUsageFlags, DidTlsPeerVerifyPolicy, DidTlsRejectReason, DidTlsRole, DidTlsTrustPolicy, DidTlsVerificationResult, DidTlsWireAlgorithm, IssueDidTlsCertificateOptions, IssuedDidTlsCertificate, MAX_CERT_BYTES, MAX_DID_TLS_CERT_BYTES, MAX_DID_TLS_DID_LENGTH, MAX_DID_TLS_PEM_CHARS, ParsedDidBindingProof, ParsedDidTlsCertificate, canonicalizeTlsDid, decodeEd25519PublicKeyPin, deriveDidTlsP256KeyPair, deriveEd25519PublicKeyFromSeed, didTlsBytesToHex, didTlsHexToBytes, extractEd25519SeedFromSecretKey, isValidW3cDidSyntax, issueDidTlsCertificate, parseDidTlsCertificate, verifyDidTlsCertificate, verifyDidTlsPeerCertificate } from "./did-tls.mjs";
|
|
4
|
+
import { ChainAppHookContext, ChainHttpTlsConfig, ChainNodeHandle, ChainNodeProfile, ChainNodeRoleConfig, ChainNodeSegmentPublisher, ChainNodeSignerConfig, ChainNodeTestHooks, ChainNodeTestHooksInput, ChainProfile, ChainProfileBase, FollowerRoleConfig, FollowerSyncTestController, FollowerUpstreamInterceptorContext, HotStuffValidatorRoleConfig, ILedgerHealthStatus, ILedgerLeaseOptions, PublicKeyOnlyValidatorSignerConfig, ReloadedTlsCredentialsInfo, RunningChainNode, StartChainNodeOptions, TNodeRetentionMode, TrustedAccountConfig, ValidatorRoleConfig, ValidatorSignerConfig } from "./types.mjs";
|
|
5
|
+
import { InstallProcessSignalHandlersOptions, assertNoSymlinkAncestors, installProcessSignalHandlers, leaseConfigFromEnv, meshEgressUrlFromEnv, roleConfigFromEnv, tlsConfigFromEnv } from "./env.mjs";
|
|
5
6
|
import { isCompleteChainConfig, rehydrateFollowerChainConfig, toResolverConfig } from "./follower-config.mjs";
|
|
6
|
-
import { startChainNode } from "./start-chain-node.mjs";
|
|
7
|
-
|
|
7
|
+
import { startChainNode, writeFileDurably } from "./start-chain-node.mjs";
|
|
8
|
+
import { ValidatedMeshEgress, createChainNodePeerFetchGuard, parseMeshEgressUrl } from "./mesh-egress.mjs";
|
|
9
|
+
export { BLOCKLET_ENV_CHAIN_FALLBACKS, type BlockletEnvLeftovers, CONSENSUS_CONFIG_KEYS, type ChainAppHookContext, type ChainHttpTlsConfig, type ChainNodeHandle, type ChainNodeProfile, type ChainNodeRoleConfig, type ChainNodeSegmentPublisher, type ChainNodeSignerConfig, type ChainNodeTestHooks, type ChainNodeTestHooksInput, type ChainProfile, type ChainProfileBase, type ConfigDifference, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_DID_TLS_CLOCK_SKEW_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, DID_TLS_BINDING_DOMAIN, DID_TLS_BINDING_PROOF_OID, DID_TLS_P256_HKDF_INFO_PREFIX, DID_TLS_P256_HKDF_SALT, type DidTlsAllowedIssuerPinsInput, type DidTlsEndpointRole, type DidTlsKeyUsageFlags, type DidTlsPeerVerifyPolicy, type DidTlsRejectReason, type DidTlsRole, type DidTlsTrustPolicy, type DidTlsVerificationResult, type DidTlsWireAlgorithm, type FollowerRoleConfig, type FollowerSyncTestController, type FollowerUpstreamInterceptorContext, type FutureTimestampGuardConfig, type HotStuffValidatorRoleConfig, type ILedgerHealthStatus, type ILedgerLeaseOptions, type InstallProcessSignalHandlersOptions, type IssueDidTlsCertificateOptions, type IssuedDidTlsCertificate, MAX_CERT_BYTES, MAX_DID_TLS_CERT_BYTES, MAX_DID_TLS_DID_LENGTH, MAX_DID_TLS_PEM_CHARS, type ParsedDidBindingProof, type ParsedDidTlsCertificate, type PublicKeyOnlyValidatorSignerConfig, type ReloadedTlsCredentialsInfo, type RunningChainNode, STANDALONE_ENV_MARKERS, type StartChainNodeOptions, type TChainConfigCheckMode, type TNodeRetentionMode, TRANSACTION_SWITCH_ENV, type TransactionSwitches, type TrustedAccountConfig, type ValidatedMeshEgress, type ValidatorRoleConfig, type ValidatorSignerConfig, type VerifyFollowerConfigOptions, type VerifyFollowerConfigResult, assertNoSymlinkAncestors, canonicalizeTlsDid, createChainNodePeerFetchGuard, decodeEd25519PublicKeyPin, deriveDidTlsP256KeyPair, deriveEd25519PublicKeyFromSeed, didTlsBytesToHex, didTlsHexToBytes, diffConsensusConfig, extractEd25519SeedFromSecretKey, fetchUpstreamChainConfig, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, formatConfigDifferences, installProcessSignalHandlers, isCompleteChainConfig, isValidW3cDidSyntax, issueDidTlsCertificate, leaseConfigFromEnv, meshEgressUrlFromEnv, normalizeConsensusConfig, parseDidTlsCertificate, parseMeshEgressUrl, parseNonNegativeNumberEnv, rehydrateFollowerChainConfig, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject, roleConfigFromEnv, startChainNode, tlsConfigFromEnv, toResolverConfig, verifyDidTlsCertificate, verifyDidTlsPeerCertificate, verifyFollowerConfigAgainstUpstream, writeFileDurably };
|
package/esm/index.mjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { CONSENSUS_CONFIG_KEYS, diffConsensusConfig, fetchUpstreamChainConfig, formatConfigDifferences, normalizeConsensusConfig, verifyFollowerConfigAgainstUpstream } from "./config-consistency.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { DEFAULT_DID_TLS_CLOCK_SKEW_SECONDS, DID_TLS_BINDING_DOMAIN, DID_TLS_BINDING_PROOF_OID, DID_TLS_P256_HKDF_INFO_PREFIX, DID_TLS_P256_HKDF_SALT, MAX_CERT_BYTES, MAX_DID_TLS_CERT_BYTES, MAX_DID_TLS_DID_LENGTH, MAX_DID_TLS_PEM_CHARS, canonicalizeTlsDid, decodeEd25519PublicKeyPin, deriveDidTlsP256KeyPair, deriveEd25519PublicKeyFromSeed, didTlsBytesToHex, didTlsHexToBytes, extractEd25519SeedFromSecretKey, isValidW3cDidSyntax, issueDidTlsCertificate, parseDidTlsCertificate, verifyDidTlsCertificate, verifyDidTlsPeerCertificate } from "./did-tls.mjs";
|
|
3
|
+
import { createChainNodePeerFetchGuard, parseMeshEgressUrl } from "./mesh-egress.mjs";
|
|
4
|
+
import { assertNoSymlinkAncestors, installProcessSignalHandlers, leaseConfigFromEnv, meshEgressUrlFromEnv, roleConfigFromEnv, tlsConfigFromEnv } from "./env.mjs";
|
|
3
5
|
import { isCompleteChainConfig, rehydrateFollowerChainConfig, toResolverConfig } from "./follower-config.mjs";
|
|
4
|
-
import { startChainNode } from "./start-chain-node.mjs";
|
|
6
|
+
import { startChainNode, writeFileDurably } from "./start-chain-node.mjs";
|
|
5
7
|
import { BLOCKLET_ENV_CHAIN_FALLBACKS, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, STANDALONE_ENV_MARKERS, TRANSACTION_SWITCH_ENV, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, parseNonNegativeNumberEnv, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject } from "./standalone-env.mjs";
|
|
6
8
|
|
|
7
|
-
export { BLOCKLET_ENV_CHAIN_FALLBACKS, CONSENSUS_CONFIG_KEYS, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, STANDALONE_ENV_MARKERS, TRANSACTION_SWITCH_ENV, diffConsensusConfig, fetchUpstreamChainConfig, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, formatConfigDifferences, installProcessSignalHandlers, isCompleteChainConfig, leaseConfigFromEnv, normalizeConsensusConfig, parseNonNegativeNumberEnv, rehydrateFollowerChainConfig, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject, roleConfigFromEnv, startChainNode, toResolverConfig, verifyFollowerConfigAgainstUpstream };
|
|
9
|
+
export { BLOCKLET_ENV_CHAIN_FALLBACKS, CONSENSUS_CONFIG_KEYS, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_DID_TLS_CLOCK_SKEW_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, DID_TLS_BINDING_DOMAIN, DID_TLS_BINDING_PROOF_OID, DID_TLS_P256_HKDF_INFO_PREFIX, DID_TLS_P256_HKDF_SALT, MAX_CERT_BYTES, MAX_DID_TLS_CERT_BYTES, MAX_DID_TLS_DID_LENGTH, MAX_DID_TLS_PEM_CHARS, STANDALONE_ENV_MARKERS, TRANSACTION_SWITCH_ENV, assertNoSymlinkAncestors, canonicalizeTlsDid, createChainNodePeerFetchGuard, decodeEd25519PublicKeyPin, deriveDidTlsP256KeyPair, deriveEd25519PublicKeyFromSeed, didTlsBytesToHex, didTlsHexToBytes, diffConsensusConfig, extractEd25519SeedFromSecretKey, fetchUpstreamChainConfig, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, formatConfigDifferences, installProcessSignalHandlers, isCompleteChainConfig, isValidW3cDidSyntax, issueDidTlsCertificate, leaseConfigFromEnv, meshEgressUrlFromEnv, normalizeConsensusConfig, parseDidTlsCertificate, parseMeshEgressUrl, parseNonNegativeNumberEnv, rehydrateFollowerChainConfig, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject, roleConfigFromEnv, startChainNode, tlsConfigFromEnv, toResolverConfig, verifyDidTlsCertificate, verifyDidTlsPeerCertificate, verifyFollowerConfigAgainstUpstream, writeFileDurably };
|
|
@@ -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 };
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
import { createFollowerPeerFetchGuard, isPrivateOrReservedIpAddress } from "@ocap/resolver";
|
|
4
|
+
|
|
5
|
+
//#region src/mesh-egress.ts
|
|
6
|
+
/**
|
|
7
|
+
* Strict validation and connect-time SSRF guard for `ARC_MESH_EGRESS_URL` / `profile.meshEgressUrl`
|
|
8
|
+
* (`@ocap/chain-node`, #2025).
|
|
9
|
+
*
|
|
10
|
+
* Allows outbound follower sync / consensus peer fetches to reach ONLY the pinned local
|
|
11
|
+
* `afs-mesh` loopback gateway (`http://127.0.0.1:<port>` or `http://[::1]:<port>`) with
|
|
12
|
+
* `redirect: 'error'`, while keeping `169.254.169.254`, `0.0.0.0`, `localhost`, and every
|
|
13
|
+
* other loopback / RFC1918 host:port 100% blocked unless `allowPrivatePeers` is enabled.
|
|
14
|
+
*/
|
|
15
|
+
const MESH_EGRESS_RAW_RE = /^http:\/\/(127\.0\.0\.1|\[::1\]):([1-9]\d{0,4})\/?$/i;
|
|
16
|
+
/**
|
|
17
|
+
* Parse and strictly validate `ARC_MESH_EGRESS_URL` / `meshEgressUrl` at config parse time.
|
|
18
|
+
* Must be `http:` on literal `127.0.0.1` or `[::1]` with an explicit port `1..65535`,
|
|
19
|
+
* no credentials, no subpath, and no query/hash.
|
|
20
|
+
*/
|
|
21
|
+
function parseMeshEgressUrl(rawUrl, label = "ARC_MESH_EGRESS_URL") {
|
|
22
|
+
if (rawUrl === void 0 || rawUrl === null) return null;
|
|
23
|
+
if (typeof rawUrl !== "string") throw new CustomError("INVALID_CONFIG", `Invalid ${label}: expected URL string`);
|
|
24
|
+
const trimmed = rawUrl.trim();
|
|
25
|
+
if (!trimmed) return null;
|
|
26
|
+
for (let i = 0; i < rawUrl.length; i++) {
|
|
27
|
+
const code = rawUrl.charCodeAt(i);
|
|
28
|
+
if (code < 32 || code === 127) throw new CustomError("INVALID_CONFIG", `Invalid ${label}: control characters are forbidden`);
|
|
29
|
+
}
|
|
30
|
+
if (/\s/.test(trimmed) || trimmed.includes("@") || trimmed.includes("\\") || trimmed.includes("?") || trimmed.includes("#")) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${trimmed}": must be http://127.0.0.1:<port> or http://[::1]:<port> with no credentials, query, or hash`);
|
|
31
|
+
const match = MESH_EGRESS_RAW_RE.exec(trimmed);
|
|
32
|
+
if (!match) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${trimmed}": expected http://127.0.0.1:<port> or http://[::1]:<port> with explicit port 1..65535`);
|
|
33
|
+
const hostname = match[1].toLowerCase();
|
|
34
|
+
const port = Number(match[2]);
|
|
35
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${trimmed}": port must be in 1..65535`);
|
|
36
|
+
const normalizedUrl = `http://${hostname}:${port}`;
|
|
37
|
+
return {
|
|
38
|
+
normalizedUrl,
|
|
39
|
+
origin: new URL(normalizedUrl).origin.toLowerCase(),
|
|
40
|
+
hostname,
|
|
41
|
+
port
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function extractRawAuthority(rawUrl) {
|
|
45
|
+
const schemeSep = rawUrl.indexOf("://");
|
|
46
|
+
if (schemeSep < 0) return null;
|
|
47
|
+
const afterScheme = rawUrl.slice(schemeSep + 3);
|
|
48
|
+
const slashIdx = afterScheme.search(/[/?#]/);
|
|
49
|
+
const authority = slashIdx >= 0 ? afterScheme.slice(0, slashIdx) : afterScheme;
|
|
50
|
+
if (!authority || authority.includes("@") || authority.includes("\\")) return null;
|
|
51
|
+
if (authority.startsWith("[")) {
|
|
52
|
+
const closeBracket = authority.indexOf("]");
|
|
53
|
+
if (closeBracket < 0) return null;
|
|
54
|
+
const rawHost = authority.slice(0, closeBracket + 1);
|
|
55
|
+
const tail = authority.slice(closeBracket + 1);
|
|
56
|
+
if (!tail) return {
|
|
57
|
+
rawHost,
|
|
58
|
+
rawPort: null
|
|
59
|
+
};
|
|
60
|
+
if (!tail.startsWith(":")) return null;
|
|
61
|
+
return {
|
|
62
|
+
rawHost,
|
|
63
|
+
rawPort: tail.slice(1)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const colonIdx = authority.indexOf(":");
|
|
67
|
+
if (colonIdx < 0) return {
|
|
68
|
+
rawHost: authority,
|
|
69
|
+
rawPort: null
|
|
70
|
+
};
|
|
71
|
+
if (authority.indexOf(":", colonIdx + 1) >= 0) return null;
|
|
72
|
+
return {
|
|
73
|
+
rawHost: authority.slice(0, colonIdx),
|
|
74
|
+
rawPort: authority.slice(colonIdx + 1)
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function isExactMeshEgressTarget(rawUrl, parsed, meshEgress) {
|
|
78
|
+
if (parsed.protocol !== "http:") return false;
|
|
79
|
+
if (parsed.username || parsed.password) return false;
|
|
80
|
+
if (parsed.origin.toLowerCase() !== meshEgress.origin) return false;
|
|
81
|
+
const auth = extractRawAuthority(rawUrl);
|
|
82
|
+
if (!auth) return false;
|
|
83
|
+
if (auth.rawHost.toLowerCase() !== meshEgress.hostname) return false;
|
|
84
|
+
if (!auth.rawPort || !/^[1-9]\d{0,4}$/.test(auth.rawPort)) return false;
|
|
85
|
+
if (Number(auth.rawPort) !== meshEgress.port) return false;
|
|
86
|
+
const rawPath = rawUrl.slice(rawUrl.indexOf("://") + 3);
|
|
87
|
+
const pathStart = rawPath.indexOf("/");
|
|
88
|
+
if (pathStart >= 0) {
|
|
89
|
+
const pathAndQuery = rawPath.slice(pathStart);
|
|
90
|
+
const qIdx = pathAndQuery.search(/[?#]/);
|
|
91
|
+
const pathnameOnly = qIdx >= 0 ? pathAndQuery.slice(0, qIdx) : pathAndQuery;
|
|
92
|
+
if (pathnameOnly.includes("\\") || pathnameOnly.includes("//") || /(?:^|\/)\.\.(?:\/|$)/.test(pathnameOnly) || /%(?:25)*(?:2e|2f|5c|00)/i.test(pathnameOnly)) return false;
|
|
93
|
+
}
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
function isForbiddenInternalOrPrivateHost(parsed) {
|
|
97
|
+
const bareHost = parsed.hostname.replace(/^\[|\]$/g, "").replace(/\.+$/g, "").toLowerCase();
|
|
98
|
+
if (!bareHost || bareHost === "localhost" || bareHost.endsWith(".localhost") || bareHost === "metadata.google.internal" || bareHost.endsWith(".internal") || bareHost === "0.0.0.0") return true;
|
|
99
|
+
if (net.isIP(bareHost) !== 0) return isPrivateOrReservedIpAddress(bareHost);
|
|
100
|
+
if (/^\d+$/.test(bareHost) || /^0x[0-9a-f]+$/i.test(bareHost)) return true;
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Create a connect-time SSRF guard for `@ocap/chain-node` outbound peer requests
|
|
105
|
+
* that pins local loopback access exclusively to `meshEgress` (`redirect: 'error'`)
|
|
106
|
+
* when `allowPrivatePeers` is false.
|
|
107
|
+
*/
|
|
108
|
+
function createChainNodePeerFetchGuard(options) {
|
|
109
|
+
const allowPrivate = Boolean(options.allowPrivatePeers);
|
|
110
|
+
const meshEgress = options.meshEgress ?? null;
|
|
111
|
+
const baseFetch = options.baseFetch ?? globalThis.fetch;
|
|
112
|
+
const safePublicStaticUrls = (options.trustedStaticUrls ?? []).filter((raw) => {
|
|
113
|
+
if (!raw || !String(raw).trim()) return false;
|
|
114
|
+
if (allowPrivate) return true;
|
|
115
|
+
try {
|
|
116
|
+
const trimmed = String(raw).trim();
|
|
117
|
+
const parsed = new URL(trimmed);
|
|
118
|
+
if (meshEgress && isExactMeshEgressTarget(trimmed, parsed, meshEgress)) return false;
|
|
119
|
+
return !isForbiddenInternalOrPrivateHost(parsed);
|
|
120
|
+
} catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
const innerGuard = createFollowerPeerFetchGuard({
|
|
125
|
+
env: { ALLOW_PRIVATE_PEER_URLS: allowPrivate ? "1" : "0" },
|
|
126
|
+
dnsLookup: options.dnsLookup,
|
|
127
|
+
trustedStaticUrls: safePublicStaticUrls,
|
|
128
|
+
baseFetch
|
|
129
|
+
});
|
|
130
|
+
return (async (input, init) => {
|
|
131
|
+
const safeInit = {
|
|
132
|
+
...init,
|
|
133
|
+
redirect: "error"
|
|
134
|
+
};
|
|
135
|
+
if (allowPrivate) return baseFetch(input, safeInit);
|
|
136
|
+
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
137
|
+
let parsed;
|
|
138
|
+
try {
|
|
139
|
+
parsed = new URL(urlStr);
|
|
140
|
+
} catch {
|
|
141
|
+
throw new CustomError("INVALID_PARAMS", `Invalid outbound peer URL: ${urlStr}`);
|
|
142
|
+
}
|
|
143
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new CustomError("SSRF_FORBIDDEN_PEER_URL", `Unsupported outbound peer URL protocol: ${parsed.protocol}`);
|
|
144
|
+
if (parsed.username || parsed.password || !extractRawAuthority(urlStr)) throw new CustomError("SSRF_FORBIDDEN_PEER_URL", "Outbound peer URL must not embed credentials or malformed host");
|
|
145
|
+
if (meshEgress && isExactMeshEgressTarget(urlStr, parsed, meshEgress)) return baseFetch(input, safeInit);
|
|
146
|
+
if (isForbiddenInternalOrPrivateHost(parsed)) throw new CustomError("SSRF_FORBIDDEN_PEER_URL", `Connect-time SSRF guard blocked non-mesh internal/private target "${parsed.origin}"`);
|
|
147
|
+
return innerGuard(input, safeInit);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
//#endregion
|
|
152
|
+
export { createChainNodePeerFetchGuard, parseMeshEgressUrl };
|
|
@@ -2,6 +2,11 @@ import { ChainNodeTestHooks, ChainProfile, RunningChainNode, StartChainNodeOptio
|
|
|
2
2
|
|
|
3
3
|
//#region src/start-chain-node.d.ts
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Write a small file atomically and durably (`wx` `0o600` temp file + `fsync` + `rename` + parent dir `fsync`),
|
|
7
|
+
* refusing symlinks on both the target file and its immediate parent directory (#2026, #2036, #2039).
|
|
8
|
+
*/
|
|
9
|
+
declare function writeFileDurably(filePath: string, content: string): void;
|
|
5
10
|
/**
|
|
6
11
|
* Boot a unified OCAP chain node (`validator`, `follower`, or `hotstuff`) with a 12-step LIFO rollback guard
|
|
7
12
|
* and 9-step reverse graceful shutdown (`docs/chain-node-design.md` §2.3–§2.4).
|
|
@@ -11,4 +16,4 @@ declare function startChainNode(profile: ChainProfile & {
|
|
|
11
16
|
testHooks?: ChainNodeTestHooks;
|
|
12
17
|
}): Promise<RunningChainNode>;
|
|
13
18
|
//#endregion
|
|
14
|
-
export { startChainNode };
|
|
19
|
+
export { startChainNode, writeFileDurably };
|