@ocap/chain-node 1.32.2 → 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/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.mjs +1 -1
- 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 +774 -47
- package/esm/types.d.mts +63 -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 +1 -1
- 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 +778 -48
- package/lib/start-chain-node.d.cts +6 -1
- package/lib/types.d.cts +62 -1
- package/package.json +16 -16
package/lib/start-chain-node.cjs
CHANGED
|
@@ -1,23 +1,30 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_access_log = require('./access-log.cjs');
|
|
3
3
|
const require_config_consistency = require('./config-consistency.cjs');
|
|
4
|
+
const require_did_tls = require('./did-tls.cjs');
|
|
5
|
+
const require_mesh_egress = require('./mesh-egress.cjs');
|
|
6
|
+
const require_env = require('./env.cjs');
|
|
4
7
|
const require_follower_config = require('./follower-config.cjs');
|
|
5
8
|
const require_test_hooks_token = require('./test-hooks-token.cjs');
|
|
6
9
|
let _ocap_util_lib_error = require("@ocap/util/lib/error");
|
|
7
|
-
let _arcblock_ledger_core = require("@arcblock/ledger-core");
|
|
8
|
-
let _arcblock_ledger_sqlite = require("@arcblock/ledger-sqlite");
|
|
9
10
|
let node_crypto = require("node:crypto");
|
|
10
11
|
node_crypto = require_rolldown_runtime.__toESM(node_crypto);
|
|
12
|
+
let _arcblock_did = require("@arcblock/did");
|
|
11
13
|
let node_fs = require("node:fs");
|
|
12
14
|
node_fs = require_rolldown_runtime.__toESM(node_fs);
|
|
13
15
|
let node_path = require("node:path");
|
|
14
16
|
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
15
|
-
let
|
|
17
|
+
let _arcblock_ledger_core = require("@arcblock/ledger-core");
|
|
18
|
+
let _arcblock_ledger_sqlite = require("@arcblock/ledger-sqlite");
|
|
19
|
+
let node_net = require("node:net");
|
|
20
|
+
node_net = require_rolldown_runtime.__toESM(node_net);
|
|
21
|
+
let _ocap_resolver = require("@ocap/resolver");
|
|
22
|
+
_ocap_resolver = require_rolldown_runtime.__toESM(_ocap_resolver);
|
|
23
|
+
let node_tls = require("node:tls");
|
|
24
|
+
node_tls = require_rolldown_runtime.__toESM(node_tls);
|
|
16
25
|
let _ocap_gql = require("@ocap/gql");
|
|
17
26
|
let _ocap_indexdb_sqlite = require("@ocap/indexdb-sqlite");
|
|
18
27
|
_ocap_indexdb_sqlite = require_rolldown_runtime.__toESM(_ocap_indexdb_sqlite);
|
|
19
|
-
let _ocap_resolver = require("@ocap/resolver");
|
|
20
|
-
_ocap_resolver = require_rolldown_runtime.__toESM(_ocap_resolver);
|
|
21
28
|
let _ocap_resolver_api = require("@ocap/resolver/api");
|
|
22
29
|
let _ocap_state = require("@ocap/state");
|
|
23
30
|
let _ocap_statedb_sqlite = require("@ocap/statedb-sqlite");
|
|
@@ -32,7 +39,132 @@ express = require_rolldown_runtime.__toESM(express);
|
|
|
32
39
|
const CHAIN_STATE_ADDR = node_crypto.default.createHash("md5").update("OCAP_CHAIN_ADDR").digest("hex");
|
|
33
40
|
const NODE_ID_FILENAME = ".node-id";
|
|
34
41
|
const DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
|
|
42
|
+
const DEFAULT_TLS_HANDSHAKE_TIMEOUT_MS = 1e4;
|
|
43
|
+
const MAX_TLS_CREDENTIAL_FILE_BYTES = 65536;
|
|
35
44
|
const FORMATTED_HOLDER_ID_RE = /:\d+:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
45
|
+
function readNonSymlinkRegularFileUtf8(rawPath, label) {
|
|
46
|
+
const resolved = node_path.default.resolve(rawPath.trim());
|
|
47
|
+
require_env.assertNoSymlinkAncestors(resolved, label);
|
|
48
|
+
let lstat;
|
|
49
|
+
try {
|
|
50
|
+
lstat = node_fs.default.lstatSync(resolved);
|
|
51
|
+
} catch (err) {
|
|
52
|
+
throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `${label} file not found (${resolved}): ${err?.code || "ENOENT"}`);
|
|
53
|
+
}
|
|
54
|
+
if (lstat.isSymbolicLink()) throw new _ocap_util_lib_error.CustomError("SECURITY_VIOLATION", `Refusing symlinked ${label} file: ${resolved}`);
|
|
55
|
+
if (!lstat.isFile()) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `${label} must be a regular file: ${resolved}`);
|
|
56
|
+
if (lstat.size === 0 || lstat.size > MAX_TLS_CREDENTIAL_FILE_BYTES) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `${label} file size (${lstat.size}B) out of range 1..${MAX_TLS_CREDENTIAL_FILE_BYTES}`);
|
|
57
|
+
const openFlags = node_fs.default.constants.O_RDONLY | (node_fs.default.constants.O_NOFOLLOW ?? 0);
|
|
58
|
+
let fd;
|
|
59
|
+
try {
|
|
60
|
+
fd = node_fs.default.openSync(resolved, openFlags);
|
|
61
|
+
} catch (err) {
|
|
62
|
+
if (err?.code === "ELOOP") throw new _ocap_util_lib_error.CustomError("SECURITY_VIOLATION", `Refusing symlinked ${label} file: ${resolved}`);
|
|
63
|
+
throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Failed to open ${label} file (${resolved}): ${err?.code || "EIO"}`);
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
const fstat = node_fs.default.fstatSync(fd);
|
|
67
|
+
if (!fstat.isFile() || fstat.size === 0 || fstat.size > MAX_TLS_CREDENTIAL_FILE_BYTES) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label} file descriptor state: ${resolved}`);
|
|
68
|
+
const buf = new Uint8Array(fstat.size);
|
|
69
|
+
const bytesRead = node_fs.default.readSync(fd, buf, 0, fstat.size, 0);
|
|
70
|
+
return new TextDecoder().decode(buf.subarray(0, bytesRead));
|
|
71
|
+
} finally {
|
|
72
|
+
node_fs.default.closeSync(fd);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function buildChainTlsSecureContextOptions(certPem, keyPem) {
|
|
76
|
+
return {
|
|
77
|
+
minVersion: "TLSv1.3",
|
|
78
|
+
maxVersion: "TLSv1.3",
|
|
79
|
+
secureOptions: node_crypto.default.constants.SSL_OP_NO_TICKET,
|
|
80
|
+
cert: certPem,
|
|
81
|
+
key: keyPem
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function countPinnedIssuers(pins) {
|
|
85
|
+
if (!pins) return 0;
|
|
86
|
+
if (pins instanceof Map) {
|
|
87
|
+
for (const [didKey, pkVal] of pins.entries()) {
|
|
88
|
+
require_did_tls.canonicalizeTlsDid(didKey, "allowedIssuerPublicKeys DID");
|
|
89
|
+
require_did_tls.decodeEd25519PublicKeyPin(pkVal, "allowedIssuerPublicKeys pubkey");
|
|
90
|
+
}
|
|
91
|
+
return pins.size;
|
|
92
|
+
}
|
|
93
|
+
if (Array.isArray(pins) || pins instanceof Set) {
|
|
94
|
+
let count = 0;
|
|
95
|
+
for (const item of pins) {
|
|
96
|
+
if (typeof item === "string" && item.includes("=")) {
|
|
97
|
+
const eq = item.indexOf("=");
|
|
98
|
+
require_did_tls.canonicalizeTlsDid(item.slice(0, eq), "allowedIssuerPublicKeys DID");
|
|
99
|
+
require_did_tls.decodeEd25519PublicKeyPin(item.slice(eq + 1), "allowedIssuerPublicKeys pubkey");
|
|
100
|
+
} else require_did_tls.decodeEd25519PublicKeyPin(item, "allowedIssuerPublicKeys pubkey");
|
|
101
|
+
count++;
|
|
102
|
+
}
|
|
103
|
+
return count;
|
|
104
|
+
}
|
|
105
|
+
if (typeof pins === "object") {
|
|
106
|
+
const entries = Object.entries(pins);
|
|
107
|
+
for (const [didKey, pkVal] of entries) {
|
|
108
|
+
require_did_tls.canonicalizeTlsDid(didKey, "allowedIssuerPublicKeys DID");
|
|
109
|
+
require_did_tls.decodeEd25519PublicKeyPin(pkVal, "allowedIssuerPublicKeys pubkey");
|
|
110
|
+
}
|
|
111
|
+
return entries.length;
|
|
112
|
+
}
|
|
113
|
+
return 0;
|
|
114
|
+
}
|
|
115
|
+
function validateChainHttpTlsConfig(rawTls) {
|
|
116
|
+
if (!rawTls?.enabled) return null;
|
|
117
|
+
const wireAlgorithm = rawTls.wireAlgorithm ?? "p256";
|
|
118
|
+
if (wireAlgorithm !== "ed25519" && wireAlgorithm !== "p256") throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid http.tls.wireAlgorithm="${String(wireAlgorithm)}"`);
|
|
119
|
+
const requireClientCert = rawTls.requireClientCert !== false;
|
|
120
|
+
const handshakeTimeoutMs = typeof rawTls.handshakeTimeoutMs === "number" && Number.isFinite(rawTls.handshakeTimeoutMs) && rawTls.handshakeTimeoutMs >= 500 ? Math.trunc(rawTls.handshakeTimeoutMs) : DEFAULT_TLS_HANDSHAKE_TIMEOUT_MS;
|
|
121
|
+
const certFile = rawTls.certFile?.trim() || void 0;
|
|
122
|
+
const keyFile = rawTls.keyFile?.trim() || void 0;
|
|
123
|
+
if (Boolean(certFile) !== Boolean(keyFile)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "http.tls.certFile and http.tls.keyFile must both be provided together");
|
|
124
|
+
if (certFile && keyFile) {
|
|
125
|
+
readNonSymlinkRegularFileUtf8(certFile, "http.tls.certFile");
|
|
126
|
+
readNonSymlinkRegularFileUtf8(keyFile, "http.tls.keyFile");
|
|
127
|
+
}
|
|
128
|
+
let pinCount = 0;
|
|
129
|
+
try {
|
|
130
|
+
pinCount = countPinnedIssuers(rawTls.allowedIssuerPublicKeys);
|
|
131
|
+
} catch (err) {
|
|
132
|
+
throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid http.tls.allowedIssuerPublicKeys: ${err instanceof Error ? err.message : String(err)}`);
|
|
133
|
+
}
|
|
134
|
+
if (requireClientCert && pinCount === 0) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "DID-TLS requireClientCert=true requires at least one pinned Ed25519 key in http.tls.allowedIssuerPublicKeys");
|
|
135
|
+
const allowedClientDids = [];
|
|
136
|
+
for (const rawDid of rawTls.allowedClientDids ?? []) try {
|
|
137
|
+
allowedClientDids.push(require_did_tls.canonicalizeTlsDid(rawDid, "http.tls.allowedClientDids"));
|
|
138
|
+
} catch (err) {
|
|
139
|
+
throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid DID in http.tls.allowedClientDids: ${err instanceof Error ? err.message : String(err)}`);
|
|
140
|
+
}
|
|
141
|
+
let subjectDid;
|
|
142
|
+
if (rawTls.subjectDid?.trim()) try {
|
|
143
|
+
subjectDid = require_did_tls.canonicalizeTlsDid(rawTls.subjectDid, "http.tls.subjectDid");
|
|
144
|
+
} catch (err) {
|
|
145
|
+
throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid http.tls.subjectDid: ${err instanceof Error ? err.message : String(err)}`);
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
enabled: true,
|
|
149
|
+
wireAlgorithm,
|
|
150
|
+
requireClientCert,
|
|
151
|
+
hasConfiguredClientTrustPins: pinCount > 0,
|
|
152
|
+
handshakeTimeoutMs,
|
|
153
|
+
...certFile ? { certFile } : {},
|
|
154
|
+
...keyFile ? { keyFile } : {},
|
|
155
|
+
...rawTls.identitySecretKey?.trim() ? { identitySecretKey: rawTls.identitySecretKey.trim() } : {},
|
|
156
|
+
...subjectDid ? { subjectDid } : {},
|
|
157
|
+
sanDnsNames: rawTls.sanDnsNames ?? [],
|
|
158
|
+
sanIpAddresses: rawTls.sanIpAddresses ?? [],
|
|
159
|
+
...rawTls.validityDays !== void 0 ? { validityDays: rawTls.validityDays } : {},
|
|
160
|
+
basePeerPolicy: {
|
|
161
|
+
allowedIssuerPublicKeys: rawTls.allowedIssuerPublicKeys,
|
|
162
|
+
...allowedClientDids.length > 0 ? { allowedSubjectDids: allowedClientDids } : {},
|
|
163
|
+
expectedRole: "client",
|
|
164
|
+
...rawTls.clockSkewSeconds !== void 0 ? { clockSkewSeconds: rawTls.clockSkewSeconds } : {}
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
36
168
|
function createDefaultLogger(prefix = "chain-node") {
|
|
37
169
|
return {
|
|
38
170
|
info: (...args) => console.info(`[${prefix}]`, ...args),
|
|
@@ -63,27 +195,54 @@ function classifyFetchKind(rawUrl) {
|
|
|
63
195
|
}
|
|
64
196
|
function assertSafeNonSymlinkDirectory(rawDataDir) {
|
|
65
197
|
const dataDir = node_path.default.resolve(rawDataDir);
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
if (node_fs.default.lstatSync(dataDir).
|
|
198
|
+
require_env.assertNoSymlinkAncestors(dataDir, "dataDir");
|
|
199
|
+
if (!node_fs.default.existsSync(dataDir)) node_fs.default.mkdirSync(dataDir, { recursive: true });
|
|
200
|
+
require_env.assertNoSymlinkAncestors(dataDir, "dataDir");
|
|
201
|
+
if (!node_fs.default.lstatSync(dataDir).isDirectory()) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Chain node dataDir is not a directory: ${dataDir}`);
|
|
70
202
|
return dataDir;
|
|
71
203
|
}
|
|
72
|
-
/**
|
|
204
|
+
/**
|
|
205
|
+
* Write a small file atomically and durably (`wx` `0o600` temp file + `fsync` + `rename` + parent dir `fsync`),
|
|
206
|
+
* refusing symlinks on both the target file and its immediate parent directory (#2026, #2036, #2039).
|
|
207
|
+
*/
|
|
73
208
|
function writeFileDurably(filePath, content) {
|
|
74
|
-
const
|
|
209
|
+
const resolved = node_path.default.resolve(filePath);
|
|
210
|
+
const parentDir = node_path.default.dirname(resolved);
|
|
211
|
+
const parentSt = node_fs.default.lstatSync(parentDir);
|
|
212
|
+
if (parentSt.isSymbolicLink() || !parentSt.isDirectory()) throw new _ocap_util_lib_error.CustomError("SECURITY_VIOLATION", `Refusing symlinked or non-directory parent: ${parentDir}`);
|
|
213
|
+
const assertTargetNotSymlink = () => {
|
|
214
|
+
try {
|
|
215
|
+
if (node_fs.default.lstatSync(resolved).isSymbolicLink()) throw new _ocap_util_lib_error.CustomError("SECURITY_VIOLATION", `Refusing symlinked target file: ${resolved}`);
|
|
216
|
+
} catch (err) {
|
|
217
|
+
if (err?.code !== "ENOENT") throw err;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
assertTargetNotSymlink();
|
|
221
|
+
const tmpPath = `${resolved}.tmp.${process.pid}.${node_crypto.default.randomBytes(6).toString("hex")}`;
|
|
222
|
+
const fd = node_fs.default.openSync(tmpPath, node_fs.default.constants.O_WRONLY | node_fs.default.constants.O_CREAT | node_fs.default.constants.O_EXCL | (node_fs.default.constants.O_NOFOLLOW ?? 0), 384);
|
|
223
|
+
let closed = false;
|
|
75
224
|
try {
|
|
76
225
|
node_fs.default.writeFileSync(fd, content);
|
|
77
226
|
node_fs.default.fsyncSync(fd);
|
|
78
|
-
} finally {
|
|
79
227
|
node_fs.default.closeSync(fd);
|
|
228
|
+
closed = true;
|
|
229
|
+
assertTargetNotSymlink();
|
|
230
|
+
node_fs.default.renameSync(tmpPath, resolved);
|
|
231
|
+
} catch (err) {
|
|
232
|
+
if (!closed) try {
|
|
233
|
+
node_fs.default.closeSync(fd);
|
|
234
|
+
} catch {}
|
|
235
|
+
node_fs.default.rmSync(tmpPath, { force: true });
|
|
236
|
+
throw err;
|
|
80
237
|
}
|
|
81
|
-
const dirFd = node_fs.default.openSync(node_path.default.dirname(filePath), "r");
|
|
82
238
|
try {
|
|
83
|
-
node_fs.default.
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
239
|
+
const dirFd = node_fs.default.openSync(parentDir, "r");
|
|
240
|
+
try {
|
|
241
|
+
node_fs.default.fsyncSync(dirFd);
|
|
242
|
+
} finally {
|
|
243
|
+
node_fs.default.closeSync(dirFd);
|
|
244
|
+
}
|
|
245
|
+
} catch {}
|
|
87
246
|
}
|
|
88
247
|
function loadOrCreateNodeId(dataDir, explicitNodeId) {
|
|
89
248
|
const nodeIdPath = node_path.default.join(dataDir, NODE_ID_FILENAME);
|
|
@@ -146,6 +305,10 @@ function buildFollowerNodeRoleConfig(role, resolvedSigner) {
|
|
|
146
305
|
upstreamChainUrl: role.upstreamChainUrl ?? null,
|
|
147
306
|
clusterPeerUrls: role.clusterPeerUrls ?? [],
|
|
148
307
|
snapshotBaseUrl: role.snapshotBaseUrl ?? null,
|
|
308
|
+
...role.bootstrapSource ? { bootstrapSource: role.bootstrapSource } : {},
|
|
309
|
+
...role.da ? { da: role.da } : {},
|
|
310
|
+
...role.daCrossCheck ? { daCrossCheck: role.daCrossCheck } : {},
|
|
311
|
+
...role.daCrossCheckIncomplete ? { daCrossCheckIncomplete: role.daCrossCheckIncomplete } : {},
|
|
149
312
|
trustedProposer: isHotStuffCluster ? null : hasExplicitTrustedAnchor ? role.trustedProposer ?? null : resolvedSigner?.address ?? null,
|
|
150
313
|
trustedProposerPublicKey: isHotStuffCluster ? null : hasExplicitTrustedAnchor ? role.trustedProposerPublicKey ?? null : resolvedSigner?.publicKey ?? null,
|
|
151
314
|
allowUnauthenticatedBootstrap: Boolean(role.allowUnauthenticatedBootstrap),
|
|
@@ -205,6 +368,8 @@ async function bootChainNodeOnce(params) {
|
|
|
205
368
|
if ((role.kind === "validator" || role.kind === "hotstuff") && !role.signer) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `${role.kind} role requires role.signer`);
|
|
206
369
|
if (role.kind === "hotstuff" && (!Array.isArray(role.validators) || role.validators.length === 0)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "HotStuff role requires a non-empty validators list");
|
|
207
370
|
if (role.kind === "follower" && role.orphanIndexFromSequence !== void 0 && (!Number.isSafeInteger(role.orphanIndexFromSequence) || role.orphanIndexFromSequence < 1)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `role.orphanIndexFromSequence must be a positive integer, got ${String(role.orphanIndexFromSequence)}`);
|
|
371
|
+
const effectiveMeshEgress = require_mesh_egress.parseMeshEgressUrl(profile.meshEgressUrl ?? ("meshEgressUrl" in role ? role.meshEgressUrl : void 0), "meshEgressUrl");
|
|
372
|
+
const validatedTls = validateChainHttpTlsConfig(profile.http?.tls);
|
|
208
373
|
const logger = testHooks?.logger ?? profile.logger ?? createDefaultLogger("chain-node");
|
|
209
374
|
const variadicLogger = toVariadicLogger(logger);
|
|
210
375
|
const followerExpectedChainId = "expectedChainId" in profile ? profile.expectedChainId : void 0;
|
|
@@ -271,13 +436,17 @@ async function bootChainNodeOnce(params) {
|
|
|
271
436
|
ledgerCleanupIndex = -1;
|
|
272
437
|
}
|
|
273
438
|
}
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
439
|
+
const staticTrustedUrls = [
|
|
440
|
+
role.upstreamChainUrl,
|
|
441
|
+
role.snapshotBaseUrl,
|
|
442
|
+
role.da?.baseUrl,
|
|
443
|
+
role.daCrossCheck?.baseUrl,
|
|
444
|
+
...role.clusterPeerUrls ?? []
|
|
445
|
+
].filter((u) => Boolean(u && String(u).trim()));
|
|
446
|
+
const guardedBootstrapFetch = require_mesh_egress.createChainNodePeerFetchGuard({
|
|
447
|
+
allowPrivatePeers: role.allowPrivatePeers,
|
|
448
|
+
meshEgress: effectiveMeshEgress,
|
|
449
|
+
trustedStaticUrls: staticTrustedUrls,
|
|
281
450
|
baseFetch: globalThis.fetch
|
|
282
451
|
});
|
|
283
452
|
const interceptFetch = testHooks?.followerSync?.interceptUpstreamFetch;
|
|
@@ -302,7 +471,8 @@ async function bootChainNodeOnce(params) {
|
|
|
302
471
|
ledgerPath,
|
|
303
472
|
trustedPath,
|
|
304
473
|
keyless: isKeylessFollower,
|
|
305
|
-
fetchImpl: bootstrapFetchImpl
|
|
474
|
+
fetchImpl: bootstrapFetchImpl,
|
|
475
|
+
logger: { warn: (...args) => variadicLogger.warn(...args) }
|
|
306
476
|
});
|
|
307
477
|
}
|
|
308
478
|
if (!ledgerStorage) {
|
|
@@ -384,12 +554,28 @@ async function bootChainNodeOnce(params) {
|
|
|
384
554
|
const hotstuffValidators = role.kind === "hotstuff" ? role.validators : role.kind === "follower" ? role.hotstuffValidators ?? [] : [];
|
|
385
555
|
const hotstuffQuorumThreshold = role.kind === "hotstuff" ? role.quorumThreshold : role.kind === "follower" ? role.hotstuffQuorumThreshold : void 0;
|
|
386
556
|
const hotstuffClusterConfig = role.kind === "hotstuff" || hotstuffValidators.length > 0 ? (0, _arcblock_ledger_core.toHotStuffClusterConfig)(chainConfig.chainId, hotstuffValidators, hotstuffQuorumThreshold) : void 0;
|
|
387
|
-
const
|
|
557
|
+
const daModeFromEnv = profile.da?.segmentPublisher === void 0 && role.kind !== "follower" && Boolean(profile.da?.env) && (0, _arcblock_ledger_core.isDaArchiveMode)(profile.da.env);
|
|
558
|
+
const daPublisherInputs = daModeFromEnv && role.kind === "validator" && resolvedProposer ? (0, _arcblock_ledger_core.daPublisherInputsFromEnv)({
|
|
388
559
|
env: profile.da.env,
|
|
560
|
+
chainId: chainConfig.chainId,
|
|
561
|
+
wallet: resolvedProposer.proposerWallet,
|
|
562
|
+
retentionMode: role.retentionMode ?? "archive",
|
|
563
|
+
resumeStore: (0, _arcblock_ledger_sqlite.createDaResumeFileStore)(node_path.default.join(dataDir, "da-publisher-resume.json")),
|
|
389
564
|
logger: variadicLogger
|
|
565
|
+
}) : {};
|
|
566
|
+
const segmentPublisher = profile.da?.segmentPublisher !== void 0 ? profile.da.segmentPublisher : role.kind !== "follower" && profile.da?.env ? (0, _arcblock_ledger_core.createEnvSegmentPublisher)({
|
|
567
|
+
env: profile.da.env,
|
|
568
|
+
logger: variadicLogger,
|
|
569
|
+
...daPublisherInputs,
|
|
570
|
+
...profile.da.fetchImpl ? { fetchImpl: profile.da.fetchImpl } : {}
|
|
390
571
|
}) : null;
|
|
391
572
|
const explicitColdReader = profile.da?.coldArchiveReader ?? null;
|
|
392
|
-
const
|
|
573
|
+
const followsDaArchive = role.kind === "follower" && role.bootstrapSource === "da";
|
|
574
|
+
const envColdReader = !explicitColdReader && profile.da?.env && !daModeFromEnv && !followsDaArchive ? (0, _arcblock_ledger_core.createEnvColdArchiveReader)({
|
|
575
|
+
env: profile.da.env,
|
|
576
|
+
logger: variadicLogger
|
|
577
|
+
}) : null;
|
|
578
|
+
(0, _arcblock_ledger_core.scrubDaCredentials)(profile.da?.env);
|
|
393
579
|
const coldSegmentStore = explicitColdReader ? adaptColdReaderToArchiveStore(explicitColdReader) : segmentPublisher?.getArchiveStore?.() || (envColdReader ? adaptColdReaderToArchiveStore(envColdReader) : void 0);
|
|
394
580
|
const hasExplicitTrustedAnchor = role.kind === "follower" && (role.trustedProposer != null || role.trustedProposerPublicKey != null);
|
|
395
581
|
const followerExplicitPk = role.kind === "follower" ? followerPrep?.trustedProposerPublicKey || role.trustedProposerPublicKey || null : null;
|
|
@@ -649,7 +835,24 @@ async function bootChainNodeOnce(params) {
|
|
|
649
835
|
trustedProposerPublicKey: followerPrep?.trustedProposerPublicKey || role.trustedProposerPublicKey || void 0,
|
|
650
836
|
allowUnauthenticatedLeaderFailover: Boolean(role.allowUnauthenticatedBootstrap)
|
|
651
837
|
}) : void 0;
|
|
652
|
-
const
|
|
838
|
+
const guardedFollowerRuntimeFetch = require_mesh_egress.createChainNodePeerFetchGuard({
|
|
839
|
+
allowPrivatePeers: role.allowPrivatePeers,
|
|
840
|
+
meshEgress: effectiveMeshEgress,
|
|
841
|
+
trustedStaticUrls: [
|
|
842
|
+
role.upstreamChainUrl,
|
|
843
|
+
role.snapshotBaseUrl,
|
|
844
|
+
role.da?.baseUrl,
|
|
845
|
+
...mergedPeerUrls,
|
|
846
|
+
...role.witnessSubmitUrls ?? []
|
|
847
|
+
],
|
|
848
|
+
baseFetch: globalThis.fetch
|
|
849
|
+
});
|
|
850
|
+
const coldReaderForFollower = (role.bootstrapSource === "da" && role.da ? (0, _arcblock_ledger_core.createDaFollowerSource)({
|
|
851
|
+
da: role.da,
|
|
852
|
+
proposer: role.trustedProposer ?? "",
|
|
853
|
+
proposerPublicKey: role.trustedProposerPublicKey ?? "",
|
|
854
|
+
fetchImpl: guardedFollowerRuntimeFetch
|
|
855
|
+
}) : null)?.reader ?? explicitColdReader ?? envColdReader ?? void 0;
|
|
653
856
|
followerSync = new _ocap_resolver.FollowerSyncService({
|
|
654
857
|
resolver,
|
|
655
858
|
role: role.runtimeRole ?? "follower",
|
|
@@ -675,6 +878,7 @@ async function bootChainNodeOnce(params) {
|
|
|
675
878
|
maxUpstreamStaleMs: role.maxUpstreamStaleMs,
|
|
676
879
|
startPaused: testHooks?.followerSync?.startPaused,
|
|
677
880
|
artificialPollDelayMs: testHooks?.followerSync?.artificialPollDelayMs,
|
|
881
|
+
fetchImpl: guardedFollowerRuntimeFetch,
|
|
678
882
|
interceptUpstreamFetch: testHooks?.followerSync?.interceptUpstreamFetch,
|
|
679
883
|
...profile.replayGuards?.futureTimestamp ? { futureTimestampGuard: {
|
|
680
884
|
...profile.replayGuards.futureTimestamp,
|
|
@@ -709,6 +913,23 @@ async function bootChainNodeOnce(params) {
|
|
|
709
913
|
}
|
|
710
914
|
} else if (role.kind === "hotstuff") {
|
|
711
915
|
const hotstuffStateStore = new _arcblock_ledger_sqlite.SqliteHotStuffStateStore(ledgerStorage);
|
|
916
|
+
const guardedHotStuffFetch = require_mesh_egress.createChainNodePeerFetchGuard({
|
|
917
|
+
allowPrivatePeers: role.allowPrivatePeers,
|
|
918
|
+
meshEgress: effectiveMeshEgress,
|
|
919
|
+
trustedStaticUrls: role.validators.flatMap((v) => [v.rpcUrl, v.consensusUrl]),
|
|
920
|
+
baseFetch: globalThis.fetch
|
|
921
|
+
});
|
|
922
|
+
const selfValidatorDid = resolvedProposer.address.trim();
|
|
923
|
+
const allHttpPeersMatchMeshEgress = effectiveMeshEgress !== null && role.validators.every((v) => {
|
|
924
|
+
if (v.did.trim() === selfValidatorDid) return true;
|
|
925
|
+
try {
|
|
926
|
+
const parsedConsensus = new URL(v.consensusUrl);
|
|
927
|
+
if (parsedConsensus.protocol === "https:") return true;
|
|
928
|
+
return parsedConsensus.origin.toLowerCase() === effectiveMeshEgress.origin;
|
|
929
|
+
} catch {
|
|
930
|
+
return false;
|
|
931
|
+
}
|
|
932
|
+
});
|
|
712
933
|
hotstuffRuntime = new _ocap_resolver.HotStuffNodeRuntime({
|
|
713
934
|
resolver,
|
|
714
935
|
validatorDid: resolvedProposer.address,
|
|
@@ -719,9 +940,10 @@ async function bootChainNodeOnce(params) {
|
|
|
719
940
|
consensusBindHost: role.consensusBindHost,
|
|
720
941
|
consensusPort: role.consensusPort,
|
|
721
942
|
allowPublicBind: Boolean(role.allowPublicConsensusBind),
|
|
722
|
-
allowPrivateHttpPeers: Boolean(role.allowPrivatePeers),
|
|
943
|
+
allowPrivateHttpPeers: Boolean(role.allowPrivatePeers || allHttpPeersMatchMeshEgress),
|
|
723
944
|
writePolicy: role.writePolicy ?? "forward",
|
|
724
945
|
stateStore: hotstuffStateStore,
|
|
946
|
+
fetchImpl: guardedHotStuffFetch,
|
|
725
947
|
onOutboundConsensusRequest: testHooks?.hotstuff?.onOutboundConsensusRequest ?? testHooks?.hotstuff?.interceptOutboundRpc
|
|
726
948
|
});
|
|
727
949
|
resolver.setNodeRuntime(hotstuffRuntime);
|
|
@@ -825,9 +1047,11 @@ async function bootChainNodeOnce(params) {
|
|
|
825
1047
|
});
|
|
826
1048
|
pushCleanup(async () => {
|
|
827
1049
|
isShuttingDown = true;
|
|
828
|
-
|
|
1050
|
+
server.closeAllConnections?.();
|
|
1051
|
+
if (server.listening) await new Promise((resolveClose) => {
|
|
829
1052
|
server.close(() => resolveClose());
|
|
830
1053
|
});
|
|
1054
|
+
else server.close();
|
|
831
1055
|
});
|
|
832
1056
|
app.use("/api", (0, _ocap_resolver_api.createAPIHandler)({
|
|
833
1057
|
resolver,
|
|
@@ -864,24 +1088,513 @@ async function bootChainNodeOnce(params) {
|
|
|
864
1088
|
const bindHost = profile.http.host?.trim() || "127.0.0.1";
|
|
865
1089
|
const requestedPort = profile.http.port;
|
|
866
1090
|
if (!Number.isSafeInteger(requestedPort) || requestedPort < 0 || requestedPort > 65535) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid http.port="${String(requestedPort)}": expected 0..65535`);
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
1091
|
+
let tlsServer;
|
|
1092
|
+
let publicTcpServer;
|
|
1093
|
+
const retiredTlsServers = /* @__PURE__ */ new Set();
|
|
1094
|
+
const activeTlsSockets = /* @__PURE__ */ new Set();
|
|
1095
|
+
const activeRawSockets = /* @__PURE__ */ new Set();
|
|
1096
|
+
const bridgeSockets = /* @__PURE__ */ new Set();
|
|
1097
|
+
const handshakeTimers = /* @__PURE__ */ new Map();
|
|
1098
|
+
const admittedBridgeByClientPort = /* @__PURE__ */ new Map();
|
|
1099
|
+
let reloadTlsCredentials = async () => ({
|
|
1100
|
+
reloaded: false,
|
|
1101
|
+
subjectDid: null,
|
|
1102
|
+
spkiSha256Hex: null
|
|
1103
|
+
});
|
|
1104
|
+
const closeAllTlsNetworking = async () => {
|
|
1105
|
+
for (const timer of handshakeTimers.values()) clearTimeout(timer);
|
|
1106
|
+
handshakeTimers.clear();
|
|
1107
|
+
for (const bSock of Array.from(bridgeSockets)) bSock.destroy();
|
|
1108
|
+
bridgeSockets.clear();
|
|
1109
|
+
admittedBridgeByClientPort.clear();
|
|
1110
|
+
for (const sock of Array.from(activeTlsSockets)) sock.destroy();
|
|
1111
|
+
activeTlsSockets.clear();
|
|
1112
|
+
for (const rawSock of Array.from(activeRawSockets)) rawSock.destroy();
|
|
1113
|
+
activeRawSockets.clear();
|
|
1114
|
+
const closeTasks = [];
|
|
1115
|
+
if (publicTcpServer?.listening) {
|
|
1116
|
+
const tcpSrv = publicTcpServer;
|
|
1117
|
+
closeTasks.push(new Promise((r) => tcpSrv.close(() => r())));
|
|
1118
|
+
}
|
|
1119
|
+
for (const oldTls of Array.from(retiredTlsServers)) if (oldTls.listening) closeTasks.push(new Promise((r) => oldTls.close(() => r())));
|
|
1120
|
+
retiredTlsServers.clear();
|
|
1121
|
+
if (tlsServer?.listening) {
|
|
1122
|
+
const activeSrv = tlsServer;
|
|
1123
|
+
closeTasks.push(new Promise((r) => activeSrv.close(() => r())));
|
|
1124
|
+
}
|
|
1125
|
+
server.closeAllConnections?.();
|
|
1126
|
+
if (server.listening) closeTasks.push(new Promise((r) => server.close(() => r())));
|
|
1127
|
+
else server.close();
|
|
1128
|
+
await Promise.all(closeTasks);
|
|
1129
|
+
};
|
|
1130
|
+
const loadOrSynthesizeTlsMaterial = () => {
|
|
1131
|
+
if (!validatedTls) throw new _ocap_util_lib_error.CustomError("INVALID_STATE", "TLS is not enabled on this chain node");
|
|
1132
|
+
if (validatedTls.certFile && validatedTls.keyFile) {
|
|
1133
|
+
const certPem = readNonSymlinkRegularFileUtf8(validatedTls.certFile, "http.tls.certFile");
|
|
1134
|
+
const keyPem = readNonSymlinkRegularFileUtf8(validatedTls.keyFile, "http.tls.keyFile");
|
|
1135
|
+
let subjectDid = null;
|
|
1136
|
+
let spkiSha256Hex = null;
|
|
1137
|
+
try {
|
|
1138
|
+
const parsed = require_did_tls.parseDidTlsCertificate(certPem);
|
|
1139
|
+
subjectDid = parsed.subjectDid;
|
|
1140
|
+
spkiSha256Hex = require_did_tls.didTlsBytesToHex(new Uint8Array(node_crypto.default.createHash("sha256").update(parsed.spkiDer).digest()));
|
|
1141
|
+
} catch {
|
|
1142
|
+
try {
|
|
1143
|
+
const spkiDer = new node_crypto.default.X509Certificate(certPem).publicKey.export({
|
|
1144
|
+
format: "der",
|
|
1145
|
+
type: "spki"
|
|
1146
|
+
});
|
|
1147
|
+
spkiSha256Hex = node_crypto.default.createHash("sha256").update(new Uint8Array(spkiDer)).digest("hex");
|
|
1148
|
+
} catch {}
|
|
1149
|
+
}
|
|
1150
|
+
return {
|
|
1151
|
+
certPem,
|
|
1152
|
+
keyPem,
|
|
1153
|
+
subjectDid,
|
|
1154
|
+
spkiSha256Hex
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
const proposerEd25519Sk = resolvedProposer?.signatureKeyType === "ed25519" ? resolvedProposer.secretKey : void 0;
|
|
1158
|
+
const rawSeed = validatedTls.identitySecretKey || proposerEd25519Sk || profile.storage?.trustedStorageSecretKey?.trim() || trustedSecretKey;
|
|
1159
|
+
if (!rawSeed) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "DID-TLS server certificate synthesis requires an Ed25519 secret key (CHAIN_SK / signer.secretKey / http.tls.identitySecretKey)");
|
|
1160
|
+
const issued = require_did_tls.issueDidTlsCertificate({
|
|
1161
|
+
subjectSeed: rawSeed,
|
|
1162
|
+
subjectDid: validatedTls.subjectDid ?? (proposerEd25519Sk && rawSeed === proposerEd25519Sk ? require_did_tls.canonicalizeTlsDid(resolvedProposer.address) : void 0),
|
|
1163
|
+
wireAlgorithm: validatedTls.wireAlgorithm,
|
|
1164
|
+
role: "server",
|
|
1165
|
+
dnsNames: validatedTls.sanDnsNames,
|
|
1166
|
+
ipAddresses: validatedTls.sanIpAddresses,
|
|
1167
|
+
notBefore: new Date(clockNow()),
|
|
1168
|
+
...validatedTls.validityDays !== void 0 ? { validityDays: validatedTls.validityDays } : {}
|
|
1169
|
+
});
|
|
1170
|
+
return {
|
|
1171
|
+
certPem: issued.certificatePem,
|
|
1172
|
+
keyPem: issued.privateKeyPem,
|
|
1173
|
+
subjectDid: issued.subjectDid,
|
|
1174
|
+
spkiSha256Hex: issued.spkiSha256Hex
|
|
871
1175
|
};
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
1176
|
+
};
|
|
1177
|
+
let boundPort;
|
|
1178
|
+
if (validatedTls) {
|
|
1179
|
+
const MAX_PRE_BRIDGE_BUFFER_BYTES = 65536;
|
|
1180
|
+
const GATED_HTTP_DISPATCH_EVENTS = new Set([
|
|
1181
|
+
"request",
|
|
1182
|
+
"upgrade",
|
|
1183
|
+
"checkContinue",
|
|
1184
|
+
"checkExpectation",
|
|
1185
|
+
"connect",
|
|
1186
|
+
"dropRequest"
|
|
1187
|
+
]);
|
|
1188
|
+
const initialMaterial = loadOrSynthesizeTlsMaterial();
|
|
1189
|
+
const shouldRequestClientCert = validatedTls.requireClientCert || validatedTls.hasConfiguredClientTrustPins;
|
|
1190
|
+
const needsLoopbackHttpBridge = server.listenerCount("connection") === 0;
|
|
1191
|
+
const needsAtomicTlsSwap = needsLoopbackHttpBridge || Boolean(process.versions.bun);
|
|
1192
|
+
let internalHttpPort = 0;
|
|
1193
|
+
let internalTlsPort = 0;
|
|
1194
|
+
if (needsLoopbackHttpBridge) {
|
|
1195
|
+
const isLoopbackRemoteAddress = (addr) => addr === "127.0.0.1" || addr === "::ffff:127.0.0.1";
|
|
1196
|
+
const verifyAndBindServerSocket = (srvSock) => {
|
|
1197
|
+
if (!srvSock || !isLoopbackRemoteAddress(srvSock.remoteAddress)) return;
|
|
1198
|
+
const remotePort = srvSock.remotePort;
|
|
1199
|
+
if (typeof remotePort !== "number" || remotePort <= 0) return;
|
|
1200
|
+
const entry = admittedBridgeByClientPort.get(remotePort);
|
|
1201
|
+
if (!entry || entry.bridgeSock.destroyed) return;
|
|
1202
|
+
if (entry.boundServerSocket && entry.boundServerSocket !== srvSock) return;
|
|
1203
|
+
if (!entry.boundServerSocket) {
|
|
1204
|
+
entry.boundServerSocket = srvSock;
|
|
1205
|
+
const revokePortEntry = () => {
|
|
1206
|
+
if (admittedBridgeByClientPort.get(remotePort) === entry) admittedBridgeByClientPort.delete(remotePort);
|
|
1207
|
+
};
|
|
1208
|
+
srvSock.once("close", revokePortEntry);
|
|
1209
|
+
const origDestroy = srvSock.destroy.bind(srvSock);
|
|
1210
|
+
srvSock.destroy = ((error) => {
|
|
1211
|
+
revokePortEntry();
|
|
1212
|
+
return origDestroy(error);
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
return entry;
|
|
1216
|
+
};
|
|
1217
|
+
const origEmit = server.emit.bind(server);
|
|
1218
|
+
server.emit = ((event, ...args) => {
|
|
1219
|
+
if (event === "connection") {
|
|
1220
|
+
const srvSock = args[0];
|
|
1221
|
+
if (!verifyAndBindServerSocket(srvSock)) {
|
|
1222
|
+
srvSock?.destroy();
|
|
1223
|
+
return false;
|
|
1224
|
+
}
|
|
1225
|
+
return origEmit(event, ...args);
|
|
1226
|
+
}
|
|
1227
|
+
if (GATED_HTTP_DISPATCH_EVENTS.has(event)) {
|
|
1228
|
+
const req = args[0];
|
|
1229
|
+
const extraSock = event === "upgrade" || event === "connect" || event === "dropRequest" ? args[1] : void 0;
|
|
1230
|
+
const reqSock = req?.socket ?? extraSock;
|
|
1231
|
+
const entry = verifyAndBindServerSocket(reqSock);
|
|
1232
|
+
if (!entry) {
|
|
1233
|
+
extraSock?.destroy();
|
|
1234
|
+
req?.socket?.destroy();
|
|
1235
|
+
return false;
|
|
1236
|
+
}
|
|
1237
|
+
if (entry.peer && reqSock) reqSock.didTlsPeer = entry.peer;
|
|
1238
|
+
}
|
|
1239
|
+
return origEmit(event, ...args);
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
const registerRawSocketTimer = (rawSocket) => {
|
|
1243
|
+
if (isShuttingDown) {
|
|
1244
|
+
rawSocket.destroy();
|
|
1245
|
+
return;
|
|
1246
|
+
}
|
|
1247
|
+
activeRawSockets.add(rawSocket);
|
|
1248
|
+
const timer = setTimeout(() => {
|
|
1249
|
+
handshakeTimers.delete(rawSocket);
|
|
1250
|
+
rawSocket.destroy();
|
|
1251
|
+
}, validatedTls.handshakeTimeoutMs);
|
|
1252
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
1253
|
+
handshakeTimers.set(rawSocket, timer);
|
|
1254
|
+
rawSocket.once("close", () => {
|
|
1255
|
+
const pendingTimer = handshakeTimers.get(rawSocket);
|
|
1256
|
+
if (pendingTimer) {
|
|
1257
|
+
clearTimeout(pendingTimer);
|
|
1258
|
+
handshakeTimers.delete(rawSocket);
|
|
1259
|
+
}
|
|
1260
|
+
activeRawSockets.delete(rawSocket);
|
|
1261
|
+
});
|
|
1262
|
+
rawSocket.on("error", () => {
|
|
1263
|
+
rawSocket.destroy();
|
|
1264
|
+
});
|
|
875
1265
|
};
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
1266
|
+
const clearRawSocketTimer = (rawSocket) => {
|
|
1267
|
+
if (!rawSocket) return;
|
|
1268
|
+
const pendingTimer = handshakeTimers.get(rawSocket);
|
|
1269
|
+
if (pendingTimer) {
|
|
1270
|
+
clearTimeout(pendingTimer);
|
|
1271
|
+
handshakeTimers.delete(rawSocket);
|
|
1272
|
+
}
|
|
1273
|
+
};
|
|
1274
|
+
const createConfiguredTlsServer = (certPem, keyPem) => {
|
|
1275
|
+
const srv = node_tls.default.createServer({
|
|
1276
|
+
...buildChainTlsSecureContextOptions(certPem, keyPem),
|
|
1277
|
+
requestCert: shouldRequestClientCert,
|
|
1278
|
+
rejectUnauthorized: false,
|
|
1279
|
+
handshakeTimeout: validatedTls.handshakeTimeoutMs
|
|
1280
|
+
});
|
|
1281
|
+
srv.on("connection", (rawSocket) => {
|
|
1282
|
+
registerRawSocketTimer(rawSocket);
|
|
1283
|
+
});
|
|
1284
|
+
srv.on("secureConnection", (tlsSocket) => {
|
|
1285
|
+
tlsSocket.setTimeout(0);
|
|
1286
|
+
const parentRaw = tlsSocket._parent;
|
|
1287
|
+
if (parentRaw) clearRawSocketTimer(parentRaw);
|
|
1288
|
+
else for (const [sock, pendingTimer] of handshakeTimers.entries()) if (sock.remotePort === tlsSocket.remotePort && sock.remoteAddress === tlsSocket.remoteAddress) {
|
|
1289
|
+
clearTimeout(pendingTimer);
|
|
1290
|
+
handshakeTimers.delete(sock);
|
|
1291
|
+
break;
|
|
1292
|
+
}
|
|
1293
|
+
if (isShuttingDown) {
|
|
1294
|
+
tlsSocket.destroy();
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
const pendingChunks = [];
|
|
1298
|
+
let pendingBytes = 0;
|
|
1299
|
+
let liveBridgeSock;
|
|
1300
|
+
if (needsLoopbackHttpBridge) tlsSocket.on("data", (chunk) => {
|
|
1301
|
+
const bytes = new Uint8Array(chunk);
|
|
1302
|
+
if (liveBridgeSock) {
|
|
1303
|
+
if (!liveBridgeSock.destroyed) liveBridgeSock.write(bytes);
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
pendingBytes += bytes.byteLength;
|
|
1307
|
+
if (pendingBytes > MAX_PRE_BRIDGE_BUFFER_BYTES) {
|
|
1308
|
+
pendingChunks.length = 0;
|
|
1309
|
+
tlsSocket.destroy();
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
pendingChunks.push(bytes);
|
|
1313
|
+
});
|
|
1314
|
+
else tlsSocket.pause();
|
|
1315
|
+
if (tlsSocket.getProtocol() !== "TLSv1.3" || tlsSocket.isSessionReused() === true) {
|
|
1316
|
+
pendingChunks.length = 0;
|
|
1317
|
+
logger.warn?.("[did-tls] rejected non-TLSv1.3 or resumed PSK/session-ticket connection", {
|
|
1318
|
+
protocol: tlsSocket.getProtocol(),
|
|
1319
|
+
sessionReused: tlsSocket.isSessionReused(),
|
|
1320
|
+
remoteAddress: tlsSocket.remoteAddress
|
|
1321
|
+
});
|
|
1322
|
+
tlsSocket.destroy();
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
let verifiedPeer;
|
|
1326
|
+
const peerCert = tlsSocket.getPeerCertificate(true);
|
|
1327
|
+
const peerPresentedCert = Boolean(peerCert && Object.keys(peerCert).length > 0);
|
|
1328
|
+
if (validatedTls.requireClientCert || peerPresentedCert) {
|
|
1329
|
+
const rawDer = peerCert && peerCert.raw instanceof Uint8Array && peerCert.raw.byteLength > 0 ? new Uint8Array(peerCert.raw.buffer, peerCert.raw.byteOffset, peerCert.raw.byteLength) : null;
|
|
1330
|
+
if (!rawDer) {
|
|
1331
|
+
pendingChunks.length = 0;
|
|
1332
|
+
tlsSocket.destroy();
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
const verdict = require_did_tls.verifyDidTlsPeerCertificate(rawDer, {
|
|
1336
|
+
...validatedTls.basePeerPolicy,
|
|
1337
|
+
now: clockNow()
|
|
1338
|
+
});
|
|
1339
|
+
if (!verdict.ok) {
|
|
1340
|
+
pendingChunks.length = 0;
|
|
1341
|
+
logger.warn?.("[did-tls] rejected unauthenticated TLS peer before HTTP/WS dispatch", {
|
|
1342
|
+
reason: verdict.reason,
|
|
1343
|
+
detail: verdict.detail,
|
|
1344
|
+
remoteAddress: tlsSocket.remoteAddress
|
|
1345
|
+
});
|
|
1346
|
+
tlsSocket.destroy();
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
verifiedPeer = verdict;
|
|
1350
|
+
tlsSocket.didTlsPeer = verdict;
|
|
1351
|
+
}
|
|
1352
|
+
activeTlsSockets.add(tlsSocket);
|
|
1353
|
+
tlsSocket.once("close", () => {
|
|
1354
|
+
activeTlsSockets.delete(tlsSocket);
|
|
1355
|
+
});
|
|
1356
|
+
tlsSocket.on("error", () => {
|
|
1357
|
+
tlsSocket.destroy();
|
|
1358
|
+
});
|
|
1359
|
+
if (!needsLoopbackHttpBridge) {
|
|
1360
|
+
server.emit("connection", tlsSocket);
|
|
1361
|
+
tlsSocket.resume();
|
|
1362
|
+
return;
|
|
1363
|
+
}
|
|
1364
|
+
if (internalHttpPort <= 0) {
|
|
1365
|
+
pendingChunks.length = 0;
|
|
1366
|
+
tlsSocket.destroy();
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
const bridgeSock = node_net.default.connect({
|
|
1370
|
+
host: "127.0.0.1",
|
|
1371
|
+
port: internalHttpPort
|
|
1372
|
+
});
|
|
1373
|
+
bridgeSockets.add(bridgeSock);
|
|
1374
|
+
let registeredPort;
|
|
1375
|
+
const entryObj = {
|
|
1376
|
+
bridgeSock,
|
|
1377
|
+
peer: verifiedPeer
|
|
1378
|
+
};
|
|
1379
|
+
const cleanupBridge = () => {
|
|
1380
|
+
bridgeSockets.delete(bridgeSock);
|
|
1381
|
+
if (registeredPort !== void 0) {
|
|
1382
|
+
const portKey = registeredPort;
|
|
1383
|
+
registeredPort = void 0;
|
|
1384
|
+
if (admittedBridgeByClientPort.get(portKey) === entryObj) admittedBridgeByClientPort.delete(portKey);
|
|
1385
|
+
}
|
|
1386
|
+
};
|
|
1387
|
+
bridgeSock.on("error", () => {
|
|
1388
|
+
cleanupBridge();
|
|
1389
|
+
tlsSocket.destroy();
|
|
1390
|
+
});
|
|
1391
|
+
bridgeSock.on("data", (chunk) => {
|
|
1392
|
+
if (!tlsSocket.destroyed) tlsSocket.write(new Uint8Array(chunk));
|
|
1393
|
+
});
|
|
1394
|
+
bridgeSock.once("close", () => {
|
|
1395
|
+
cleanupBridge();
|
|
1396
|
+
if (!tlsSocket.destroyed) tlsSocket.end();
|
|
1397
|
+
});
|
|
1398
|
+
tlsSocket.once("end", () => {
|
|
1399
|
+
if (!bridgeSock.destroyed) bridgeSock.end();
|
|
1400
|
+
});
|
|
1401
|
+
tlsSocket.once("close", () => {
|
|
1402
|
+
pendingChunks.length = 0;
|
|
1403
|
+
cleanupBridge();
|
|
1404
|
+
if (!bridgeSock.destroyed) bridgeSock.destroy();
|
|
1405
|
+
});
|
|
1406
|
+
bridgeSock.once("connect", () => {
|
|
1407
|
+
if (tlsSocket.destroyed || typeof bridgeSock.localPort !== "number" || bridgeSock.localPort <= 0) {
|
|
1408
|
+
pendingChunks.length = 0;
|
|
1409
|
+
cleanupBridge();
|
|
1410
|
+
bridgeSock.destroy();
|
|
1411
|
+
tlsSocket.destroy();
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
registeredPort = bridgeSock.localPort;
|
|
1415
|
+
admittedBridgeByClientPort.set(registeredPort, entryObj);
|
|
1416
|
+
liveBridgeSock = bridgeSock;
|
|
1417
|
+
for (const buffered of pendingChunks) bridgeSock.write(buffered);
|
|
1418
|
+
pendingChunks.length = 0;
|
|
1419
|
+
});
|
|
1420
|
+
});
|
|
1421
|
+
srv.on("tlsClientError", () => {});
|
|
1422
|
+
return srv;
|
|
1423
|
+
};
|
|
1424
|
+
const listenTlsLoopback = (srv) => new Promise((resolvePort, rejectPort) => {
|
|
1425
|
+
const onError = (err) => {
|
|
1426
|
+
srv.off("listening", onListening);
|
|
1427
|
+
rejectPort(err);
|
|
1428
|
+
};
|
|
1429
|
+
const onListening = () => {
|
|
1430
|
+
srv.off("error", onError);
|
|
1431
|
+
const addr = srv.address();
|
|
1432
|
+
resolvePort(addr && typeof addr === "object" ? addr.port : 0);
|
|
1433
|
+
};
|
|
1434
|
+
srv.once("error", onError);
|
|
1435
|
+
srv.once("listening", onListening);
|
|
1436
|
+
srv.listen(0, "127.0.0.1");
|
|
1437
|
+
});
|
|
1438
|
+
let activeTlsServer = createConfiguredTlsServer(initialMaterial.certPem, initialMaterial.keyPem);
|
|
1439
|
+
tlsServer = activeTlsServer;
|
|
1440
|
+
pushCleanup(async () => {
|
|
1441
|
+
isShuttingDown = true;
|
|
1442
|
+
await closeAllTlsNetworking();
|
|
1443
|
+
});
|
|
1444
|
+
if (needsLoopbackHttpBridge && !server.listening) await new Promise((resolveHttp, rejectHttp) => {
|
|
1445
|
+
const onError = (err) => {
|
|
1446
|
+
server.off("listening", onListening);
|
|
1447
|
+
rejectHttp(err);
|
|
1448
|
+
};
|
|
1449
|
+
const onListening = () => {
|
|
1450
|
+
server.off("error", onError);
|
|
1451
|
+
const bAddr = server.address();
|
|
1452
|
+
if (bAddr && typeof bAddr === "object") internalHttpPort = bAddr.port;
|
|
1453
|
+
resolveHttp();
|
|
1454
|
+
};
|
|
1455
|
+
server.once("error", onError);
|
|
1456
|
+
server.once("listening", onListening);
|
|
1457
|
+
server.listen(0, "127.0.0.1");
|
|
1458
|
+
});
|
|
1459
|
+
if (needsAtomicTlsSwap) {
|
|
1460
|
+
internalTlsPort = await listenTlsLoopback(activeTlsServer);
|
|
1461
|
+
const tcpListener = node_net.default.createServer((clientTcp) => {
|
|
1462
|
+
registerRawSocketTimer(clientTcp);
|
|
1463
|
+
if (isShuttingDown || internalTlsPort <= 0) {
|
|
1464
|
+
clientTcp.destroy();
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const upstream = node_net.default.connect({
|
|
1468
|
+
host: "127.0.0.1",
|
|
1469
|
+
port: internalTlsPort
|
|
1470
|
+
});
|
|
1471
|
+
bridgeSockets.add(upstream);
|
|
1472
|
+
const earlyTcp = [];
|
|
1473
|
+
let earlyBytes = 0;
|
|
1474
|
+
let connected = false;
|
|
1475
|
+
clientTcp.on("data", (chunk) => {
|
|
1476
|
+
clearRawSocketTimer(clientTcp);
|
|
1477
|
+
const bytes = new Uint8Array(chunk);
|
|
1478
|
+
if (connected) {
|
|
1479
|
+
if (!upstream.destroyed) upstream.write(bytes);
|
|
1480
|
+
return;
|
|
1481
|
+
}
|
|
1482
|
+
earlyBytes += bytes.byteLength;
|
|
1483
|
+
if (earlyBytes > MAX_PRE_BRIDGE_BUFFER_BYTES) {
|
|
1484
|
+
earlyTcp.length = 0;
|
|
1485
|
+
clientTcp.destroy();
|
|
1486
|
+
upstream.destroy();
|
|
1487
|
+
return;
|
|
1488
|
+
}
|
|
1489
|
+
earlyTcp.push(bytes);
|
|
1490
|
+
});
|
|
1491
|
+
let upstreamBytesSent = 0;
|
|
1492
|
+
upstream.on("error", () => {
|
|
1493
|
+
bridgeSockets.delete(upstream);
|
|
1494
|
+
clientTcp.destroy();
|
|
1495
|
+
});
|
|
1496
|
+
upstream.on("data", (chunk) => {
|
|
1497
|
+
const bytes = new Uint8Array(chunk);
|
|
1498
|
+
upstreamBytesSent += bytes.byteLength;
|
|
1499
|
+
if (!clientTcp.destroyed) clientTcp.write(bytes);
|
|
1500
|
+
});
|
|
1501
|
+
upstream.once("close", () => {
|
|
1502
|
+
bridgeSockets.delete(upstream);
|
|
1503
|
+
if (!clientTcp.destroyed) if (upstreamBytesSent === 0) clientTcp.destroy();
|
|
1504
|
+
else clientTcp.end();
|
|
1505
|
+
});
|
|
1506
|
+
clientTcp.once("end", () => {
|
|
1507
|
+
if (!upstream.destroyed) upstream.end();
|
|
1508
|
+
});
|
|
1509
|
+
clientTcp.once("close", () => {
|
|
1510
|
+
earlyTcp.length = 0;
|
|
1511
|
+
bridgeSockets.delete(upstream);
|
|
1512
|
+
if (!upstream.destroyed) upstream.destroy();
|
|
1513
|
+
});
|
|
1514
|
+
upstream.once("connect", () => {
|
|
1515
|
+
if (clientTcp.destroyed) {
|
|
1516
|
+
bridgeSockets.delete(upstream);
|
|
1517
|
+
upstream.destroy();
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1520
|
+
connected = true;
|
|
1521
|
+
for (const c of earlyTcp) upstream.write(c);
|
|
1522
|
+
earlyTcp.length = 0;
|
|
1523
|
+
});
|
|
1524
|
+
});
|
|
1525
|
+
publicTcpServer = tcpListener;
|
|
1526
|
+
await new Promise((resolveListen, rejectListen) => {
|
|
1527
|
+
const onError = (err) => {
|
|
1528
|
+
tcpListener.off("listening", onListening);
|
|
1529
|
+
rejectListen(err);
|
|
1530
|
+
};
|
|
1531
|
+
const onListening = () => {
|
|
1532
|
+
tcpListener.off("error", onError);
|
|
1533
|
+
resolveListen();
|
|
1534
|
+
};
|
|
1535
|
+
tcpListener.once("error", onError);
|
|
1536
|
+
tcpListener.once("listening", onListening);
|
|
1537
|
+
tcpListener.listen(requestedPort, bindHost);
|
|
1538
|
+
});
|
|
1539
|
+
const tcpAddr = tcpListener.address();
|
|
1540
|
+
boundPort = tcpAddr && typeof tcpAddr === "object" && typeof tcpAddr.port === "number" ? tcpAddr.port : requestedPort;
|
|
1541
|
+
} else {
|
|
1542
|
+
await new Promise((resolveListen, rejectListen) => {
|
|
1543
|
+
const onError = (err) => {
|
|
1544
|
+
activeTlsServer.off("listening", onListening);
|
|
1545
|
+
rejectListen(err);
|
|
1546
|
+
};
|
|
1547
|
+
const onListening = () => {
|
|
1548
|
+
activeTlsServer.off("error", onError);
|
|
1549
|
+
resolveListen();
|
|
1550
|
+
};
|
|
1551
|
+
activeTlsServer.once("error", onError);
|
|
1552
|
+
activeTlsServer.once("listening", onListening);
|
|
1553
|
+
activeTlsServer.listen(requestedPort, bindHost);
|
|
1554
|
+
});
|
|
1555
|
+
const tlsAddr = activeTlsServer.address();
|
|
1556
|
+
boundPort = tlsAddr && typeof tlsAddr === "object" && typeof tlsAddr.port === "number" ? tlsAddr.port : requestedPort;
|
|
1557
|
+
}
|
|
1558
|
+
reloadTlsCredentials = async () => {
|
|
1559
|
+
const refreshed = loadOrSynthesizeTlsMaterial();
|
|
1560
|
+
if (needsAtomicTlsSwap && activeTlsServer.listening) {
|
|
1561
|
+
const nextTlsServer = createConfiguredTlsServer(refreshed.certPem, refreshed.keyPem);
|
|
1562
|
+
const nextPort = await listenTlsLoopback(nextTlsServer);
|
|
1563
|
+
const previousTlsServer = activeTlsServer;
|
|
1564
|
+
activeTlsServer = nextTlsServer;
|
|
1565
|
+
tlsServer = nextTlsServer;
|
|
1566
|
+
internalTlsPort = nextPort;
|
|
1567
|
+
retiredTlsServers.add(previousTlsServer);
|
|
1568
|
+
previousTlsServer.close(() => {
|
|
1569
|
+
retiredTlsServers.delete(previousTlsServer);
|
|
1570
|
+
});
|
|
1571
|
+
} else activeTlsServer.setSecureContext(buildChainTlsSecureContextOptions(refreshed.certPem, refreshed.keyPem));
|
|
1572
|
+
return {
|
|
1573
|
+
reloaded: true,
|
|
1574
|
+
subjectDid: refreshed.subjectDid,
|
|
1575
|
+
spkiSha256Hex: refreshed.spkiSha256Hex
|
|
1576
|
+
};
|
|
1577
|
+
};
|
|
1578
|
+
} else {
|
|
1579
|
+
await new Promise((resolveListen, rejectListen) => {
|
|
1580
|
+
const onError = (err) => {
|
|
1581
|
+
server.off("listening", onListening);
|
|
1582
|
+
rejectListen(err);
|
|
1583
|
+
};
|
|
1584
|
+
const onListening = () => {
|
|
1585
|
+
server.off("error", onError);
|
|
1586
|
+
resolveListen();
|
|
1587
|
+
};
|
|
1588
|
+
server.once("error", onError);
|
|
1589
|
+
server.once("listening", onListening);
|
|
1590
|
+
server.listen(requestedPort, bindHost);
|
|
1591
|
+
});
|
|
1592
|
+
const addressInfo = server.address();
|
|
1593
|
+
boundPort = addressInfo && typeof addressInfo === "object" && typeof addressInfo.port === "number" ? addressInfo.port : requestedPort;
|
|
1594
|
+
}
|
|
882
1595
|
const urlHost = formatHttpHostForUrl(bindHost);
|
|
883
|
-
const endpoint =
|
|
884
|
-
const wsUrl =
|
|
1596
|
+
const endpoint = `${validatedTls ? "https" : "http"}://${urlHost}:${boundPort}`;
|
|
1597
|
+
const wsUrl = `${validatedTls ? "wss" : "ws"}://${urlHost}:${boundPort}`;
|
|
885
1598
|
if (testHooks?.onAfterBoot) await testHooks.onAfterBoot({
|
|
886
1599
|
dataDir,
|
|
887
1600
|
statedb,
|
|
@@ -922,7 +1635,8 @@ async function bootChainNodeOnce(params) {
|
|
|
922
1635
|
isShuttingDown = true;
|
|
923
1636
|
server.closeIdleConnections?.();
|
|
924
1637
|
await waitForActiveHttpDrain();
|
|
925
|
-
|
|
1638
|
+
if (validatedTls) await closeAllTlsNetworking();
|
|
1639
|
+
else await new Promise((resolveClose) => {
|
|
926
1640
|
server.close(() => resolveClose());
|
|
927
1641
|
});
|
|
928
1642
|
await resolver.shutdown().catch(captureErr);
|
|
@@ -986,10 +1700,14 @@ async function bootChainNodeOnce(params) {
|
|
|
986
1700
|
indexdb,
|
|
987
1701
|
trustedStorage,
|
|
988
1702
|
server,
|
|
1703
|
+
get tlsServer() {
|
|
1704
|
+
return tlsServer;
|
|
1705
|
+
},
|
|
989
1706
|
...followerSync ? { followerSync } : {},
|
|
990
1707
|
...hotstuffRuntime ? { hotstuffRuntime } : {},
|
|
991
1708
|
preferencesManager,
|
|
992
1709
|
maintenanceController,
|
|
1710
|
+
reloadTlsCredentials,
|
|
993
1711
|
stop
|
|
994
1712
|
};
|
|
995
1713
|
} catch (err) {
|
|
@@ -1086,6 +1804,9 @@ async function startChainNode(optionsOrProfile) {
|
|
|
1086
1804
|
get server() {
|
|
1087
1805
|
return currentBooted.server;
|
|
1088
1806
|
},
|
|
1807
|
+
get tlsServer() {
|
|
1808
|
+
return currentBooted.tlsServer;
|
|
1809
|
+
},
|
|
1089
1810
|
get followerSync() {
|
|
1090
1811
|
return currentBooted.followerSync;
|
|
1091
1812
|
},
|
|
@@ -1101,15 +1822,23 @@ async function startChainNode(optionsOrProfile) {
|
|
|
1101
1822
|
async ledgerHealth() {
|
|
1102
1823
|
return currentBooted.ledger.getHealth();
|
|
1103
1824
|
},
|
|
1825
|
+
async reloadTlsCredentials() {
|
|
1826
|
+
return withLifecycleLock(async () => currentBooted.reloadTlsCredentials());
|
|
1827
|
+
},
|
|
1104
1828
|
...advanceClockFn ? { advanceClock: advanceClockFn } : {},
|
|
1105
1829
|
async restart(nextProfile) {
|
|
1106
1830
|
return withLifecycleLock(async () => {
|
|
1107
1831
|
const previousPort = currentBooted.port;
|
|
1108
1832
|
await currentBooted.stop();
|
|
1833
|
+
const mergedTls = nextProfile?.http && "tls" in nextProfile.http ? nextProfile.http.tls ? {
|
|
1834
|
+
...currentProfile.http.tls ?? {},
|
|
1835
|
+
...nextProfile.http.tls
|
|
1836
|
+
} : void 0 : currentProfile.http.tls;
|
|
1109
1837
|
const mergedHttp = {
|
|
1110
1838
|
...currentProfile.http,
|
|
1111
1839
|
...nextProfile?.http ?? {},
|
|
1112
|
-
port: nextProfile?.http?.port !== void 0 ? nextProfile.http.port : previousPort
|
|
1840
|
+
port: nextProfile?.http?.port !== void 0 ? nextProfile.http.port : previousPort,
|
|
1841
|
+
...mergedTls !== void 0 ? { tls: mergedTls } : { tls: void 0 }
|
|
1113
1842
|
};
|
|
1114
1843
|
const mergedProfile = {
|
|
1115
1844
|
...currentProfile,
|
|
@@ -1159,4 +1888,5 @@ async function startChainNode(optionsOrProfile) {
|
|
|
1159
1888
|
}
|
|
1160
1889
|
|
|
1161
1890
|
//#endregion
|
|
1162
|
-
exports.startChainNode = startChainNode;
|
|
1891
|
+
exports.startChainNode = startChainNode;
|
|
1892
|
+
exports.writeFileDurably = writeFileDurably;
|