@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/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,12 +195,55 @@ 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
|
}
|
|
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
|
+
*/
|
|
208
|
+
function writeFileDurably(filePath, content) {
|
|
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;
|
|
224
|
+
try {
|
|
225
|
+
node_fs.default.writeFileSync(fd, content);
|
|
226
|
+
node_fs.default.fsyncSync(fd);
|
|
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;
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
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 {}
|
|
246
|
+
}
|
|
72
247
|
function loadOrCreateNodeId(dataDir, explicitNodeId) {
|
|
73
248
|
const nodeIdPath = node_path.default.join(dataDir, NODE_ID_FILENAME);
|
|
74
249
|
if (node_fs.default.existsSync(nodeIdPath) && node_fs.default.lstatSync(nodeIdPath).isSymbolicLink()) throw new _ocap_util_lib_error.CustomError("SECURITY_VIOLATION", `Refusing symlinked .node-id file: ${nodeIdPath}`);
|
|
@@ -130,6 +305,10 @@ function buildFollowerNodeRoleConfig(role, resolvedSigner) {
|
|
|
130
305
|
upstreamChainUrl: role.upstreamChainUrl ?? null,
|
|
131
306
|
clusterPeerUrls: role.clusterPeerUrls ?? [],
|
|
132
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 } : {},
|
|
133
312
|
trustedProposer: isHotStuffCluster ? null : hasExplicitTrustedAnchor ? role.trustedProposer ?? null : resolvedSigner?.address ?? null,
|
|
134
313
|
trustedProposerPublicKey: isHotStuffCluster ? null : hasExplicitTrustedAnchor ? role.trustedProposerPublicKey ?? null : resolvedSigner?.publicKey ?? null,
|
|
135
314
|
allowUnauthenticatedBootstrap: Boolean(role.allowUnauthenticatedBootstrap),
|
|
@@ -188,6 +367,9 @@ async function bootChainNodeOnce(params) {
|
|
|
188
367
|
if ((role.kind === "validator" || role.kind === "hotstuff") && !require_follower_config.isCompleteChainConfig(profile.chainConfig)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `${role.kind} role requires a complete chainConfig`);
|
|
189
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`);
|
|
190
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");
|
|
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);
|
|
191
373
|
const logger = testHooks?.logger ?? profile.logger ?? createDefaultLogger("chain-node");
|
|
192
374
|
const variadicLogger = toVariadicLogger(logger);
|
|
193
375
|
const followerExpectedChainId = "expectedChainId" in profile ? profile.expectedChainId : void 0;
|
|
@@ -235,6 +417,7 @@ async function bootChainNodeOnce(params) {
|
|
|
235
417
|
let ledgerCleanupIndex = -1;
|
|
236
418
|
let followerPrep = null;
|
|
237
419
|
const isKeylessFollower = role.kind === "follower" && !profile.storage?.trustedStorageSecretKey?.trim();
|
|
420
|
+
let followerFetchGuard;
|
|
238
421
|
if (role.kind === "follower") {
|
|
239
422
|
if (node_fs.default.existsSync(ledgerPath) && node_fs.default.statSync(ledgerPath).size > 0) {
|
|
240
423
|
const precheckLedgerStorage = createLedgerStorage();
|
|
@@ -253,13 +436,17 @@ async function bootChainNodeOnce(params) {
|
|
|
253
436
|
ledgerCleanupIndex = -1;
|
|
254
437
|
}
|
|
255
438
|
}
|
|
256
|
-
const
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
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,
|
|
263
450
|
baseFetch: globalThis.fetch
|
|
264
451
|
});
|
|
265
452
|
const interceptFetch = testHooks?.followerSync?.interceptUpstreamFetch;
|
|
@@ -271,6 +458,7 @@ async function bootChainNodeOnce(params) {
|
|
|
271
458
|
init
|
|
272
459
|
}, guardedBootstrapFetch);
|
|
273
460
|
}) : guardedBootstrapFetch;
|
|
461
|
+
followerFetchGuard = bootstrapFetchImpl;
|
|
274
462
|
const explicitExpectedChainId = followerExpectedChainId?.trim() || "";
|
|
275
463
|
const profileChainId = profile.chainConfig?.chainId?.trim() || "";
|
|
276
464
|
if (explicitExpectedChainId && profileChainId && explicitExpectedChainId !== profileChainId) throw new _ocap_util_lib_error.CustomError("SNAPSHOT_CHAIN_ID_MISMATCH", `Follower expectedChainId (${explicitExpectedChainId}) !== profile.chainConfig.chainId (${profileChainId})`);
|
|
@@ -283,7 +471,8 @@ async function bootChainNodeOnce(params) {
|
|
|
283
471
|
ledgerPath,
|
|
284
472
|
trustedPath,
|
|
285
473
|
keyless: isKeylessFollower,
|
|
286
|
-
fetchImpl: bootstrapFetchImpl
|
|
474
|
+
fetchImpl: bootstrapFetchImpl,
|
|
475
|
+
logger: { warn: (...args) => variadicLogger.warn(...args) }
|
|
287
476
|
});
|
|
288
477
|
}
|
|
289
478
|
if (!ledgerStorage) {
|
|
@@ -350,7 +539,7 @@ async function bootChainNodeOnce(params) {
|
|
|
350
539
|
const storedChainId = typeof storedChainPartial.chainId === "string" ? storedChainPartial.chainId.trim() : "";
|
|
351
540
|
const overrideChainId = typeof profile.chainConfig?.chainId === "string" ? profile.chainConfig.chainId.trim() : "";
|
|
352
541
|
if (storedChainId && overrideChainId && overrideChainId !== storedChainId) throw new _ocap_util_lib_error.CustomError("SNAPSHOT_CHAIN_ID_MISMATCH", `Follower profile.chainConfig.chainId (${overrideChainId}) !== statedb chain.chainId (${storedChainId})`);
|
|
353
|
-
chainConfig = require_follower_config.rehydrateFollowerChainConfig(storedChain, profile.chainConfig);
|
|
542
|
+
chainConfig = require_follower_config.rehydrateFollowerChainConfig(storedChain, profile.chainConfig, profile.reservedSymbols);
|
|
354
543
|
} else {
|
|
355
544
|
const baseConfig = profile.chainConfig;
|
|
356
545
|
if (role.kind === "follower") {
|
|
@@ -361,15 +550,32 @@ async function bootChainNodeOnce(params) {
|
|
|
361
550
|
chainConfig = baseConfig;
|
|
362
551
|
}
|
|
363
552
|
if (role.kind === "follower" && followerExpectedChainId && chainConfig.chainId !== followerExpectedChainId) throw new _ocap_util_lib_error.CustomError("SNAPSHOT_CHAIN_ID_MISMATCH", `Rehydrated Follower chainId (${chainConfig.chainId}) !== expectedChainId (${followerExpectedChainId})`);
|
|
553
|
+
const orphanIndexStart = role.kind === "follower" ? require_follower_config.orphanIndexFromSequence(chainConfig.chainId, role.orphanIndexFromSequence) : 1;
|
|
364
554
|
const hotstuffValidators = role.kind === "hotstuff" ? role.validators : role.kind === "follower" ? role.hotstuffValidators ?? [] : [];
|
|
365
555
|
const hotstuffQuorumThreshold = role.kind === "hotstuff" ? role.quorumThreshold : role.kind === "follower" ? role.hotstuffQuorumThreshold : void 0;
|
|
366
556
|
const hotstuffClusterConfig = role.kind === "hotstuff" || hotstuffValidators.length > 0 ? (0, _arcblock_ledger_core.toHotStuffClusterConfig)(chainConfig.chainId, hotstuffValidators, hotstuffQuorumThreshold) : void 0;
|
|
367
|
-
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)({
|
|
368
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")),
|
|
369
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 } : {}
|
|
370
571
|
}) : null;
|
|
371
572
|
const explicitColdReader = profile.da?.coldArchiveReader ?? null;
|
|
372
|
-
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);
|
|
373
579
|
const coldSegmentStore = explicitColdReader ? adaptColdReaderToArchiveStore(explicitColdReader) : segmentPublisher?.getArchiveStore?.() || (envColdReader ? adaptColdReaderToArchiveStore(envColdReader) : void 0);
|
|
374
580
|
const hasExplicitTrustedAnchor = role.kind === "follower" && (role.trustedProposer != null || role.trustedProposerPublicKey != null);
|
|
375
581
|
const followerExplicitPk = role.kind === "follower" ? followerPrep?.trustedProposerPublicKey || role.trustedProposerPublicKey || null : null;
|
|
@@ -529,6 +735,9 @@ async function bootChainNodeOnce(params) {
|
|
|
529
735
|
});
|
|
530
736
|
}
|
|
531
737
|
const indexDbExisted = node_fs.default.existsSync(indexdbPath);
|
|
738
|
+
const indexBuildMarkerPath = `${indexdbPath}.build-pending`;
|
|
739
|
+
let followerIndexBuildNeeded = role.kind === "follower" && (Boolean(followerPrep?.bootstrapped) || !indexDbExisted || node_fs.default.existsSync(indexBuildMarkerPath));
|
|
740
|
+
if (followerIndexBuildNeeded) writeFileDurably(indexBuildMarkerPath, `${(/* @__PURE__ */ new Date()).toISOString()}\n`);
|
|
532
741
|
const indexdb = new _ocap_indexdb_sqlite.default({
|
|
533
742
|
filename: indexdbPath,
|
|
534
743
|
...profile.storage?.indexWalAutoCheckpoint !== void 0 ? { walAutoCheckpoint: profile.storage.indexWalAutoCheckpoint } : {}
|
|
@@ -538,8 +747,16 @@ async function bootChainNodeOnce(params) {
|
|
|
538
747
|
});
|
|
539
748
|
await indexdb.initialize();
|
|
540
749
|
await waitEventEmitterReady(indexdb);
|
|
750
|
+
if (role.kind === "follower" && !followerIndexBuildNeeded) {
|
|
751
|
+
if (await indexdb.tx.count() === 0 && await ledger.getLatestSequence() > 0) {
|
|
752
|
+
logger.warn?.("follower IndexDB has no transactions while the ledger has entries; rebuilding it", { indexdbPath });
|
|
753
|
+
followerIndexBuildNeeded = true;
|
|
754
|
+
writeFileDurably(indexBuildMarkerPath, `${(/* @__PURE__ */ new Date()).toISOString()}\n`);
|
|
755
|
+
}
|
|
756
|
+
}
|
|
541
757
|
let resolverRef = null;
|
|
542
|
-
const
|
|
758
|
+
const explicitAdminEnv = profile.http.adminEnv;
|
|
759
|
+
const adminEnv = explicitAdminEnv ?? {};
|
|
543
760
|
const preferencesManager = new _ocap_resolver.NodePreferencesManager({
|
|
544
761
|
dataDir,
|
|
545
762
|
env: adminEnv,
|
|
@@ -599,7 +816,7 @@ async function bootChainNodeOnce(params) {
|
|
|
599
816
|
mode: profile.configCheck?.mode ?? "off",
|
|
600
817
|
localConfig: resolver.config,
|
|
601
818
|
upstreamUrl: role.upstreamChainUrl ?? role.clusterPeerUrls?.[0] ?? null,
|
|
602
|
-
fetchUpstreamConfig: profile.configCheck?.fetchUpstreamConfig,
|
|
819
|
+
fetchUpstreamConfig: profile.configCheck?.fetchUpstreamConfig ?? ((u) => require_config_consistency.fetchUpstreamChainConfig(u, followerFetchGuard ? { fetchImpl: followerFetchGuard } : void 0)),
|
|
603
820
|
hasLocalState: !followerPrep?.bootstrapped && await ledger.getLatestSequence() > 0,
|
|
604
821
|
...profile.configCheck?.retryDeadlineMs !== void 0 ? { retryDeadlineMs: profile.configCheck.retryDeadlineMs } : {},
|
|
605
822
|
logger
|
|
@@ -618,7 +835,24 @@ async function bootChainNodeOnce(params) {
|
|
|
618
835
|
trustedProposerPublicKey: followerPrep?.trustedProposerPublicKey || role.trustedProposerPublicKey || void 0,
|
|
619
836
|
allowUnauthenticatedLeaderFailover: Boolean(role.allowUnauthenticatedBootstrap)
|
|
620
837
|
}) : void 0;
|
|
621
|
-
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;
|
|
622
856
|
followerSync = new _ocap_resolver.FollowerSyncService({
|
|
623
857
|
resolver,
|
|
624
858
|
role: role.runtimeRole ?? "follower",
|
|
@@ -644,6 +878,7 @@ async function bootChainNodeOnce(params) {
|
|
|
644
878
|
maxUpstreamStaleMs: role.maxUpstreamStaleMs,
|
|
645
879
|
startPaused: testHooks?.followerSync?.startPaused,
|
|
646
880
|
artificialPollDelayMs: testHooks?.followerSync?.artificialPollDelayMs,
|
|
881
|
+
fetchImpl: guardedFollowerRuntimeFetch,
|
|
647
882
|
interceptUpstreamFetch: testHooks?.followerSync?.interceptUpstreamFetch,
|
|
648
883
|
...profile.replayGuards?.futureTimestamp ? { futureTimestampGuard: {
|
|
649
884
|
...profile.replayGuards.futureTimestamp,
|
|
@@ -661,12 +896,40 @@ async function bootChainNodeOnce(params) {
|
|
|
661
896
|
triggerSyncOnce: () => syncRef.triggerSyncOnce()
|
|
662
897
|
});
|
|
663
898
|
}
|
|
664
|
-
if (
|
|
665
|
-
|
|
666
|
-
|
|
899
|
+
if (followerIndexBuildNeeded) {
|
|
900
|
+
const buildStart = Date.now();
|
|
901
|
+
logger.info?.("follower initial index build started", {
|
|
902
|
+
indexdbPath,
|
|
903
|
+
resumed: indexDbExisted
|
|
904
|
+
});
|
|
905
|
+
const built = await resolver.rebuildIndex();
|
|
906
|
+
const orphans = await followerSync.replayer.indexExistingOrphanEntries(orphanIndexStart);
|
|
907
|
+
node_fs.default.rmSync(indexBuildMarkerPath, { force: true });
|
|
908
|
+
logger.info?.("follower initial index build finished", {
|
|
909
|
+
tables: built?.tables,
|
|
910
|
+
orphanEntries: orphans,
|
|
911
|
+
durationMs: Date.now() - buildStart
|
|
912
|
+
});
|
|
667
913
|
}
|
|
668
914
|
} else if (role.kind === "hotstuff") {
|
|
669
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
|
+
});
|
|
670
933
|
hotstuffRuntime = new _ocap_resolver.HotStuffNodeRuntime({
|
|
671
934
|
resolver,
|
|
672
935
|
validatorDid: resolvedProposer.address,
|
|
@@ -677,9 +940,10 @@ async function bootChainNodeOnce(params) {
|
|
|
677
940
|
consensusBindHost: role.consensusBindHost,
|
|
678
941
|
consensusPort: role.consensusPort,
|
|
679
942
|
allowPublicBind: Boolean(role.allowPublicConsensusBind),
|
|
680
|
-
allowPrivateHttpPeers: Boolean(role.allowPrivatePeers),
|
|
943
|
+
allowPrivateHttpPeers: Boolean(role.allowPrivatePeers || allHttpPeersMatchMeshEgress),
|
|
681
944
|
writePolicy: role.writePolicy ?? "forward",
|
|
682
945
|
stateStore: hotstuffStateStore,
|
|
946
|
+
fetchImpl: guardedHotStuffFetch,
|
|
683
947
|
onOutboundConsensusRequest: testHooks?.hotstuff?.onOutboundConsensusRequest ?? testHooks?.hotstuff?.interceptOutboundRpc
|
|
684
948
|
});
|
|
685
949
|
resolver.setNodeRuntime(hotstuffRuntime);
|
|
@@ -733,7 +997,7 @@ async function bootChainNodeOnce(params) {
|
|
|
733
997
|
res.once("close", markDone);
|
|
734
998
|
next();
|
|
735
999
|
});
|
|
736
|
-
if (profile.http.enableAccessLog) app.use(require_access_log.createAccessLogMiddleware(logger));
|
|
1000
|
+
if (profile.http.enableAccessLog) app.use(require_access_log.createAccessLogMiddleware(logger, explicitAdminEnv ? { env: explicitAdminEnv } : void 0));
|
|
737
1001
|
app.head("/", (_req, res) => {
|
|
738
1002
|
res.status(200).send("OK");
|
|
739
1003
|
});
|
|
@@ -776,13 +1040,18 @@ async function bootChainNodeOnce(params) {
|
|
|
776
1040
|
const server = (0, _ocap_gql.createSocketHandler)({
|
|
777
1041
|
indexdb,
|
|
778
1042
|
app,
|
|
779
|
-
wsOptions: {
|
|
1043
|
+
wsOptions: {
|
|
1044
|
+
broadcastEventName: `@arcblock/ws:broadcast:${nodeId}:${node_crypto.default.randomUUID()}`,
|
|
1045
|
+
...explicitAdminEnv ? { env: explicitAdminEnv } : {}
|
|
1046
|
+
}
|
|
780
1047
|
});
|
|
781
1048
|
pushCleanup(async () => {
|
|
782
1049
|
isShuttingDown = true;
|
|
783
|
-
|
|
1050
|
+
server.closeAllConnections?.();
|
|
1051
|
+
if (server.listening) await new Promise((resolveClose) => {
|
|
784
1052
|
server.close(() => resolveClose());
|
|
785
1053
|
});
|
|
1054
|
+
else server.close();
|
|
786
1055
|
});
|
|
787
1056
|
app.use("/api", (0, _ocap_resolver_api.createAPIHandler)({
|
|
788
1057
|
resolver,
|
|
@@ -811,6 +1080,7 @@ async function bootChainNodeOnce(params) {
|
|
|
811
1080
|
});
|
|
812
1081
|
app.use("/", (0, _ocap_gql.createHttpHandler)({
|
|
813
1082
|
resolver,
|
|
1083
|
+
...explicitAdminEnv ? { env: explicitAdminEnv } : {},
|
|
814
1084
|
onError: profile.http.onGraphqlError ? (err) => {
|
|
815
1085
|
profile.http.onGraphqlError(err);
|
|
816
1086
|
} : () => {}
|
|
@@ -818,24 +1088,513 @@ async function bootChainNodeOnce(params) {
|
|
|
818
1088
|
const bindHost = profile.http.host?.trim() || "127.0.0.1";
|
|
819
1089
|
const requestedPort = profile.http.port;
|
|
820
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`);
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
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
|
|
1175
|
+
};
|
|
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
|
+
});
|
|
825
1265
|
};
|
|
826
|
-
const
|
|
827
|
-
|
|
828
|
-
|
|
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
|
+
}
|
|
829
1273
|
};
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
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
|
+
}
|
|
836
1595
|
const urlHost = formatHttpHostForUrl(bindHost);
|
|
837
|
-
const endpoint =
|
|
838
|
-
const wsUrl =
|
|
1596
|
+
const endpoint = `${validatedTls ? "https" : "http"}://${urlHost}:${boundPort}`;
|
|
1597
|
+
const wsUrl = `${validatedTls ? "wss" : "ws"}://${urlHost}:${boundPort}`;
|
|
839
1598
|
if (testHooks?.onAfterBoot) await testHooks.onAfterBoot({
|
|
840
1599
|
dataDir,
|
|
841
1600
|
statedb,
|
|
@@ -876,7 +1635,8 @@ async function bootChainNodeOnce(params) {
|
|
|
876
1635
|
isShuttingDown = true;
|
|
877
1636
|
server.closeIdleConnections?.();
|
|
878
1637
|
await waitForActiveHttpDrain();
|
|
879
|
-
|
|
1638
|
+
if (validatedTls) await closeAllTlsNetworking();
|
|
1639
|
+
else await new Promise((resolveClose) => {
|
|
880
1640
|
server.close(() => resolveClose());
|
|
881
1641
|
});
|
|
882
1642
|
await resolver.shutdown().catch(captureErr);
|
|
@@ -940,10 +1700,14 @@ async function bootChainNodeOnce(params) {
|
|
|
940
1700
|
indexdb,
|
|
941
1701
|
trustedStorage,
|
|
942
1702
|
server,
|
|
1703
|
+
get tlsServer() {
|
|
1704
|
+
return tlsServer;
|
|
1705
|
+
},
|
|
943
1706
|
...followerSync ? { followerSync } : {},
|
|
944
1707
|
...hotstuffRuntime ? { hotstuffRuntime } : {},
|
|
945
1708
|
preferencesManager,
|
|
946
1709
|
maintenanceController,
|
|
1710
|
+
reloadTlsCredentials,
|
|
947
1711
|
stop
|
|
948
1712
|
};
|
|
949
1713
|
} catch (err) {
|
|
@@ -1040,6 +1804,9 @@ async function startChainNode(optionsOrProfile) {
|
|
|
1040
1804
|
get server() {
|
|
1041
1805
|
return currentBooted.server;
|
|
1042
1806
|
},
|
|
1807
|
+
get tlsServer() {
|
|
1808
|
+
return currentBooted.tlsServer;
|
|
1809
|
+
},
|
|
1043
1810
|
get followerSync() {
|
|
1044
1811
|
return currentBooted.followerSync;
|
|
1045
1812
|
},
|
|
@@ -1055,15 +1822,23 @@ async function startChainNode(optionsOrProfile) {
|
|
|
1055
1822
|
async ledgerHealth() {
|
|
1056
1823
|
return currentBooted.ledger.getHealth();
|
|
1057
1824
|
},
|
|
1825
|
+
async reloadTlsCredentials() {
|
|
1826
|
+
return withLifecycleLock(async () => currentBooted.reloadTlsCredentials());
|
|
1827
|
+
},
|
|
1058
1828
|
...advanceClockFn ? { advanceClock: advanceClockFn } : {},
|
|
1059
1829
|
async restart(nextProfile) {
|
|
1060
1830
|
return withLifecycleLock(async () => {
|
|
1061
1831
|
const previousPort = currentBooted.port;
|
|
1062
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;
|
|
1063
1837
|
const mergedHttp = {
|
|
1064
1838
|
...currentProfile.http,
|
|
1065
1839
|
...nextProfile?.http ?? {},
|
|
1066
|
-
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 }
|
|
1067
1842
|
};
|
|
1068
1843
|
const mergedProfile = {
|
|
1069
1844
|
...currentProfile,
|
|
@@ -1113,4 +1888,5 @@ async function startChainNode(optionsOrProfile) {
|
|
|
1113
1888
|
}
|
|
1114
1889
|
|
|
1115
1890
|
//#endregion
|
|
1116
|
-
exports.startChainNode = startChainNode;
|
|
1891
|
+
exports.startChainNode = startChainNode;
|
|
1892
|
+
exports.writeFileDurably = writeFileDurably;
|