@ocap/resolver 1.32.0 → 1.32.2
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/explorer.mjs +12 -3
- package/esm/follower.d.mts +18 -1
- package/esm/follower.mjs +39 -9
- package/esm/hooks.mjs +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/index.mjs +3 -3
- package/esm/node-preferences.mjs +7 -6
- package/esm/replayer.d.mts +58 -6
- package/esm/replayer.mjs +102 -34
- package/lib/explorer.cjs +13 -3
- package/lib/follower.cjs +38 -8
- package/lib/follower.d.cts +18 -1
- package/lib/hooks.cjs +2 -2
- package/lib/index.cjs +3 -2
- package/lib/index.d.cts +2 -2
- package/lib/node-preferences.cjs +6 -5
- package/lib/replayer.cjs +104 -33
- package/lib/replayer.d.cts +58 -6
- package/package.json +16 -15
package/esm/replayer.mjs
CHANGED
|
@@ -4,6 +4,9 @@ import { createExecutor } from "@ocap/tx-protocols";
|
|
|
4
4
|
import { fromBase64 } from "@ocap/util";
|
|
5
5
|
import { CustomError } from "@ocap/util/lib/error";
|
|
6
6
|
import { Blacklist } from "@ocap/state";
|
|
7
|
+
import { pipes } from "@ocap/tx-pipeline";
|
|
8
|
+
import cloneDeep from "lodash/cloneDeep.js";
|
|
9
|
+
import merge from "lodash/merge.js";
|
|
7
10
|
|
|
8
11
|
//#region src/replayer.ts
|
|
9
12
|
/**
|
|
@@ -21,6 +24,8 @@ import { Blacklist } from "@ocap/state";
|
|
|
21
24
|
* - Enforces pre-commit `expectedCommitHash` on `statedb.runAsLambda` so any state divergence rolls back
|
|
22
25
|
* SQLite atomically BEFORE `COMMIT` and before appending to `ledger.sqlite`.
|
|
23
26
|
*/
|
|
27
|
+
/** Error code of a replayed entry refused for a timestamp ahead of the local clock (retryable, never halting). */
|
|
28
|
+
const FUTURE_LEDGER_ENTRY_TIMESTAMP = "FUTURE_LEDGER_ENTRY_TIMESTAMP";
|
|
24
29
|
function normalizeHexLower(raw) {
|
|
25
30
|
return String(raw ?? "").trim().replace(/^0x/i, "").toLowerCase();
|
|
26
31
|
}
|
|
@@ -43,7 +48,7 @@ function isLocalStorageEngineError(err, depth = 0) {
|
|
|
43
48
|
return cause !== void 0 && cause !== err ? isLocalStorageEngineError(cause, depth + 1) : false;
|
|
44
49
|
}
|
|
45
50
|
var LedgerEntryReplayer = class {
|
|
46
|
-
constructor(resolver) {
|
|
51
|
+
constructor(resolver, options = {}) {
|
|
47
52
|
this.activeSubLambdaOverride = null;
|
|
48
53
|
this.lastCommittedHash = null;
|
|
49
54
|
this.lastCommitMismatchError = null;
|
|
@@ -51,6 +56,12 @@ var LedgerEntryReplayer = class {
|
|
|
51
56
|
this.mutex = Promise.resolve();
|
|
52
57
|
this.resolver = resolver;
|
|
53
58
|
this.emptyFilter = new Blacklist();
|
|
59
|
+
const guard = options.futureTimestampGuard;
|
|
60
|
+
if (guard) {
|
|
61
|
+
if (!Number.isSafeInteger(guard.activationSequence) || guard.activationSequence < 1) throw new CustomError("INVALID_CONFIG", `futureTimestampGuard.activationSequence must be a positive integer, got ${String(guard.activationSequence)}`);
|
|
62
|
+
if (!Number.isSafeInteger(guard.maxSkewMs) || guard.maxSkewMs < 0) throw new CustomError("INVALID_CONFIG", `futureTimestampGuard.maxSkewMs must be a non-negative integer, got ${String(guard.maxSkewMs)}`);
|
|
63
|
+
}
|
|
64
|
+
this.futureTimestampGuard = guard ? { ...guard } : null;
|
|
54
65
|
const statedb = resolver.statedb;
|
|
55
66
|
const runAsLambda = typeof statedb.runAsLambda === "function" ? async (fn, opts = {}) => {
|
|
56
67
|
const expectedCommitHash = this.activeExpectedCommitHash;
|
|
@@ -140,39 +151,75 @@ var LedgerEntryReplayer = class {
|
|
|
140
151
|
if (computedTxHash.toUpperCase() !== entry.hash.toUpperCase()) throw new CustomError(throwCodeOnMismatch, `Ledger entry txRaw hash mismatch at seq=${entry.sequence}: computed ${computedTxHash}, entry has ${entry.hash}`);
|
|
141
152
|
}
|
|
142
153
|
/**
|
|
154
|
+
* #1961 future-timestamp guard (no-op unless `futureTimestampGuard` is configured). Throws a retryable
|
|
155
|
+
* `FUTURE_LEDGER_ENTRY_TIMESTAMP` that is neither a local divergence nor a peer authentication failure, so the
|
|
156
|
+
* follower logs it, keeps its state and retries on the next sync cycle.
|
|
157
|
+
*/
|
|
158
|
+
assertEntryTimestampNotInFuture(entry) {
|
|
159
|
+
const guard = this.futureTimestampGuard;
|
|
160
|
+
if (!guard || !Number.isSafeInteger(entry?.sequence) || entry.sequence < guard.activationSequence) return;
|
|
161
|
+
const nowMs = guard.now ? guard.now() : Date.now();
|
|
162
|
+
if (!Number.isFinite(nowMs) || entry.timestamp <= nowMs + guard.maxSkewMs) return;
|
|
163
|
+
const info = {
|
|
164
|
+
sequence: entry.sequence,
|
|
165
|
+
hash: String(entry.hash ?? ""),
|
|
166
|
+
timestamp: entry.timestamp,
|
|
167
|
+
nowMs,
|
|
168
|
+
maxSkewMs: guard.maxSkewMs,
|
|
169
|
+
activationSequence: guard.activationSequence
|
|
170
|
+
};
|
|
171
|
+
try {
|
|
172
|
+
guard.onReject?.(info);
|
|
173
|
+
} catch {}
|
|
174
|
+
const err = new CustomError(FUTURE_LEDGER_ENTRY_TIMESTAMP, `Ledger entry seq=${entry.sequence} timestamp ${entry.timestamp} is ${entry.timestamp - nowMs} ms ahead of the local clock (max skew ${guard.maxSkewMs} ms, guard active from seq=${guard.activationSequence}); will retry`);
|
|
175
|
+
err.retryable = true;
|
|
176
|
+
throw err;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
143
179
|
* Pre-replay wire & primitive validation for untrusted network hot-tail / cold-segment payloads (#1710).
|
|
144
|
-
* Throws `INVALID_LEDGER_ENTRY` (peer-disqualifying, non-halting) on any malformed wire field or lossy JSON coercion
|
|
180
|
+
* Throws `INVALID_LEDGER_ENTRY` (peer-disqualifying, non-halting) on any malformed wire field or lossy JSON coercion,
|
|
181
|
+
* and the retryable `FUTURE_LEDGER_ENTRY_TIMESTAMP` when the #1961 guard is on (unless the entry is local).
|
|
145
182
|
*/
|
|
146
|
-
validateWireEntry(entry) {
|
|
183
|
+
validateWireEntry(entry, options = {}) {
|
|
147
184
|
if (!entry || typeof entry !== "object" || !Number.isSafeInteger(entry.sequence) || entry.sequence < 1 || !Number.isSafeInteger(entry.nonce) || entry.nonce < 0 || !Number.isSafeInteger(entry.timestamp) || entry.timestamp < 0 || entry.timestamp > 864e13 || typeof entry.hash !== "string" || typeof entry.from !== "string" || typeof entry.pk !== "string" || typeof entry.signature !== "string" || typeof entry.txRaw !== "string" || typeof entry.txType !== "string" || typeof entry.chainId !== "string" || typeof entry.entryHash !== "string" || typeof entry.finalized !== "boolean" || entry.stateCommitHash !== void 0 && typeof entry.stateCommitHash !== "string" || entry.tx === null || typeof entry.tx !== "object" || Array.isArray(entry.tx)) throw new CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${String(entry?.sequence)} has invalid wire primitive types`);
|
|
148
185
|
this.verifyRawTxHashMatchesEntry(entry, "INVALID_LEDGER_ENTRY");
|
|
149
186
|
this.authenticateAndDecodeEntry(entry);
|
|
187
|
+
if (!options.skipFutureTimestampCheck) this.assertEntryTimestampNotInFuture(entry);
|
|
150
188
|
}
|
|
151
189
|
authenticateAndDecodeEntry(entry) {
|
|
152
190
|
const authRes = authenticateEntryDecodedFields(entry, true, { requireFullWireEntry: true });
|
|
153
|
-
if (!authRes.ok) throw new CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${entry.sequence} failed field authentication: ${authRes.reason}`);
|
|
191
|
+
if (!authRes.ok) throw new CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${entry.sequence} hash=${String(entry.hash)} failed field authentication: ${authRes.reason}`);
|
|
154
192
|
return authRes.decodedTx;
|
|
155
193
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
|
|
194
|
+
/**
|
|
195
|
+
* Index a rejected-but-ledgered entry (finalized, no stateCommitHash) with the row the leader wrote for it: the
|
|
196
|
+
* leader's `sendTx` passes the context of its `DecodeTx` + `DecodeItx` pipes to `_indexRejectedLedgerTx`, so the
|
|
197
|
+
* follower builds that context from the entry's txRaw with the same pipes and the time pinned to the entry
|
|
198
|
+
* (#1875). Only the rejection code differs: it is not in the ledger, so the row says `ORPHAN_LEDGER_ENTRY`.
|
|
199
|
+
*/
|
|
200
|
+
async indexOrphanEntry(entry) {
|
|
201
|
+
const ctx = {
|
|
202
|
+
txBase64: entry.txRaw,
|
|
203
|
+
config: this.resolver.config,
|
|
204
|
+
extra: { txTime: entry.timestamp }
|
|
205
|
+
};
|
|
206
|
+
const runPipe = (pipe) => new Promise((resolve, reject) => {
|
|
207
|
+
try {
|
|
208
|
+
pipe(ctx, (err) => err ? reject(err) : resolve());
|
|
209
|
+
} catch (err) {
|
|
210
|
+
reject(err);
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
try {
|
|
214
|
+
await runPipe(pipes.DecodeTx);
|
|
215
|
+
await runPipe(pipes.DecodeItx);
|
|
216
|
+
} catch (err) {
|
|
217
|
+
throw new CustomError("INVALID_LEDGER_ENTRY", `Orphan ledger entry seq=${entry.sequence} hash=${entry.hash} does not decode as the leader decodes it: ${err instanceof Error ? err.message : String(err)}`);
|
|
218
|
+
}
|
|
219
|
+
if (String(ctx.txHash ?? "").toUpperCase() !== String(entry.hash).toUpperCase()) throw new CustomError("TX_HASH_MISMATCH", `Orphan ledger entry seq=${entry.sequence} hash=${entry.hash}: txRaw does not hash to its entry hash`);
|
|
220
|
+
const leaderCtx = merge(cloneDeep(ctx), ctx);
|
|
221
|
+
leaderCtx.ledgerSequence = entry.sequence;
|
|
222
|
+
await this.resolver._indexRejectedLedgerTx(leaderCtx, { code: "ORPHAN_LEDGER_ENTRY" });
|
|
176
223
|
await this.resolver.flushIndexWrites();
|
|
177
224
|
}
|
|
178
225
|
/**
|
|
@@ -203,8 +250,9 @@ var LedgerEntryReplayer = class {
|
|
|
203
250
|
}
|
|
204
251
|
if (entry.sequence !== localLatestSeq + 1) throw new CustomError("SEQUENCE_GAP", `Non-contiguous replay sequence: localLatest=${localLatestSeq}, got seq=${entry.sequence}`);
|
|
205
252
|
}
|
|
253
|
+
if (appendToLedger) this.assertEntryTimestampNotInFuture(entry);
|
|
206
254
|
this.verifyRawTxHashMatchesEntry(entry);
|
|
207
|
-
|
|
255
|
+
this.authenticateAndDecodeEntry(entry);
|
|
208
256
|
const expectedStateCommit = (entry.stateCommitHash ?? "").trim();
|
|
209
257
|
if (appendToLedger) {
|
|
210
258
|
const v2Cutoff = options.entryHashV2From === "infinity" ? Number.POSITIVE_INFINITY : typeof options.entryHashV2From === "number" ? options.entryHashV2From : this.resolver.ledger.getEntryHashV2From?.() ?? 1;
|
|
@@ -213,7 +261,7 @@ var LedgerEntryReplayer = class {
|
|
|
213
261
|
}
|
|
214
262
|
if (!expectedStateCommit) {
|
|
215
263
|
if (appendToLedger) await this.appendVerifiedEntryToLedger(entry, options.entryHashV2From);
|
|
216
|
-
await this.indexOrphanEntry(entry
|
|
264
|
+
await this.indexOrphanEntry(entry);
|
|
217
265
|
return {
|
|
218
266
|
status: "orphan-indexed",
|
|
219
267
|
sequence: entry.sequence,
|
|
@@ -294,7 +342,7 @@ var LedgerEntryReplayer = class {
|
|
|
294
342
|
if (entry.finalized !== true) throw new CustomError("UNFINALIZED_LEDGER_ENTRY", `Proposal entry seq=${String(entry.sequence)} must be finalized`);
|
|
295
343
|
if (entry.chainId !== expectedChainId) throw new CustomError("CHAIN_ID_MISMATCH", `Proposal entry chainId mismatch at seq=${String(entry.sequence)}: expected ${expectedChainId}, got ${entry.chainId}`);
|
|
296
344
|
if (entry.sequence !== baseSeq + i + 1) throw new CustomError("SEQUENCE_GAP", `Proposal entry sequence mismatch at index ${i}: expected ${baseSeq + i + 1}, got ${entry.sequence}`);
|
|
297
|
-
this.validateWireEntry(entry);
|
|
345
|
+
this.validateWireEntry(entry, { skipFutureTimestampCheck: options.skipFutureTimestampCheck });
|
|
298
346
|
const expectedStateCommit = (entry.stateCommitHash ?? "").trim();
|
|
299
347
|
const expectedEntryHash = computeEntryHash(entry.sequence, entry.txRaw, expectedStateCommit, entry.sequence >= v2Cutoff ? 2 : 1);
|
|
300
348
|
if (entry.entryHash !== expectedEntryHash) throw new CustomError("INVALID_LEDGER_ENTRY", `Proposal entryHash mismatch at seq=${entry.sequence}: expected ${expectedEntryHash}, got ${entry.entryHash}`);
|
|
@@ -367,9 +415,27 @@ var LedgerEntryReplayer = class {
|
|
|
367
415
|
};
|
|
368
416
|
});
|
|
369
417
|
}
|
|
418
|
+
/** Upper-cased hashes of `entries` that neither `indexdb.tx` nor `statedb.tx` holds (one `$in` count per page). */
|
|
419
|
+
async hashesMissingFromIndex(entries) {
|
|
420
|
+
const missing = /* @__PURE__ */ new Set();
|
|
421
|
+
if (entries.length === 0) return missing;
|
|
422
|
+
const hashes = [...new Set(entries.map((e) => String(e.hash).toUpperCase()))];
|
|
423
|
+
const { indexdb, statedb } = this.resolver;
|
|
424
|
+
if (await indexdb.tx.count({ hash: { $in: hashes } }) === hashes.length) return missing;
|
|
425
|
+
for (const hash of hashes) {
|
|
426
|
+
if (await indexdb.tx.count({ hash }) > 0) continue;
|
|
427
|
+
if (await Promise.resolve(statedb?.tx?.get?.(hash))) continue;
|
|
428
|
+
missing.add(hash);
|
|
429
|
+
}
|
|
430
|
+
return missing;
|
|
431
|
+
}
|
|
370
432
|
/**
|
|
371
|
-
*
|
|
372
|
-
* orphan
|
|
433
|
+
* After `rebuildIndex()`, index the force-finalized orphan entries of `[fromSeq, toSeq]` that the index does not
|
|
434
|
+
* have yet. An orphan is an entry without a `stateCommitHash` (its tx never reached the statedb, so the build
|
|
435
|
+
* from the statedb cannot see it) whose tx is in neither `indexdb.tx` nor `statedb.tx`. Entries the index already
|
|
436
|
+
* holds are skipped before any decoding: beta's ledger starts with 434k migrated entries without a
|
|
437
|
+
* `stateCommitHash` and in a legacy entry shape, all indexed by the build (#1875). Every entry that is processed
|
|
438
|
+
* is authenticated as before and fails closed.
|
|
373
439
|
*/
|
|
374
440
|
async indexExistingOrphanEntries(fromSeq = 1, toSeq) {
|
|
375
441
|
const latestSeq = toSeq ?? await this.resolver.ledger.getLatestSequence();
|
|
@@ -378,11 +444,13 @@ var LedgerEntryReplayer = class {
|
|
|
378
444
|
const pageSize = 200;
|
|
379
445
|
for (let cursor = Math.max(1, fromSeq); cursor <= latestSeq; cursor += pageSize) {
|
|
380
446
|
const end = Math.min(latestSeq, cursor + pageSize - 1);
|
|
381
|
-
const
|
|
382
|
-
|
|
447
|
+
const candidates = (await this.resolver.ledger.getRange(cursor, end)).filter((entry) => !entry.stateCommitHash || !entry.stateCommitHash.trim());
|
|
448
|
+
const missing = await this.hashesMissingFromIndex(candidates);
|
|
449
|
+
for (const entry of candidates) {
|
|
450
|
+
if (!missing.has(String(entry.hash).toUpperCase())) continue;
|
|
383
451
|
this.verifyRawTxHashMatchesEntry(entry);
|
|
384
|
-
|
|
385
|
-
await this.indexOrphanEntry(entry
|
|
452
|
+
this.authenticateAndDecodeEntry(entry);
|
|
453
|
+
await this.indexOrphanEntry(entry);
|
|
386
454
|
indexedCount++;
|
|
387
455
|
}
|
|
388
456
|
}
|
|
@@ -391,4 +459,4 @@ var LedgerEntryReplayer = class {
|
|
|
391
459
|
};
|
|
392
460
|
|
|
393
461
|
//#endregion
|
|
394
|
-
export { LedgerEntryReplayer };
|
|
462
|
+
export { FUTURE_LEDGER_ENTRY_TIMESTAMP, LedgerEntryReplayer };
|
package/lib/explorer.cjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
1
2
|
const require_dashboard = require('./dashboard.cjs');
|
|
3
|
+
let _ocap_util_lib_client_ip = require("@ocap/util/lib/client-ip");
|
|
2
4
|
|
|
3
5
|
//#region src/explorer.ts
|
|
4
6
|
function loadNodeBuiltin(id) {
|
|
@@ -119,8 +121,15 @@ function createExplorerMiddleware(options) {
|
|
|
119
121
|
if (verifiedDistRealPath && reqPath === "/static/js/networks.js") {
|
|
120
122
|
const cfg = options.getConfig() ?? {};
|
|
121
123
|
const chainId = String(cfg.chainId || "local-chain");
|
|
122
|
-
const
|
|
123
|
-
const
|
|
124
|
+
const rawHost = String(req.get?.("host") || req.headers?.host || "").trim();
|
|
125
|
+
const safeHost = rawHost.length > 0 && rawHost.length <= 255 && (/^[A-Za-z0-9.-]+(?::\d{1,5})?$/.test(rawHost) || /^\[[0-9a-fA-F:]+\](?::\d{1,5})?$/.test(rawHost)) ? rawHost : "127.0.0.1";
|
|
126
|
+
let scheme = req.protocol === "https" ? "https" : "http";
|
|
127
|
+
if (scheme === "http" && (0, _ocap_util_lib_client_ip.isLoopbackAddress)(req.socket?.remoteAddress)) {
|
|
128
|
+
const xfProto = String(req.headers?.["x-forwarded-proto"] || "").split(",")[0].trim().toLowerCase();
|
|
129
|
+
const cfVisitor = String(req.headers?.["cf-visitor"] || "");
|
|
130
|
+
if (xfProto === "https" || /"scheme"\s*:\s*"https"/i.test(cfVisitor)) scheme = "https";
|
|
131
|
+
}
|
|
132
|
+
const endpoint = /^https?:\/\//.test(chainEndpoint) ? chainEndpoint : `${scheme}://${safeHost}${chainEndpoint.startsWith("/") ? "" : "/"}${chainEndpoint.replace(/\/+$/, "")}/`;
|
|
124
133
|
const networks = [{
|
|
125
134
|
name: chainId,
|
|
126
135
|
abbr: cfg.token?.symbol || "ARC",
|
|
@@ -130,7 +139,8 @@ function createExplorerMiddleware(options) {
|
|
|
130
139
|
}];
|
|
131
140
|
applyExplorerSecurityHeaders(res, false);
|
|
132
141
|
res.setHeader("Content-Type", "application/javascript; charset=utf-8");
|
|
133
|
-
res.setHeader("Cache-Control", "no-
|
|
142
|
+
res.setHeader("Cache-Control", "no-store");
|
|
143
|
+
res.setHeader("Vary", "Host, X-Forwarded-Proto, CF-Visitor");
|
|
134
144
|
return res.status(200).send(`window.ARCBLOCK_NETWORKS = ${safeJsonForJsLiteral(networks)};\n`);
|
|
135
145
|
}
|
|
136
146
|
if (reqPath === "/static/js/networks.js") {
|
package/lib/follower.cjs
CHANGED
|
@@ -145,7 +145,8 @@ const UPSTREAM_OR_TRANSPORT_ERROR_CODES = new Set([
|
|
|
145
145
|
"COLD_SEGMENT_CHAIN_MISMATCH",
|
|
146
146
|
"INVALID_LEDGER_ENTRY",
|
|
147
147
|
"UNFINALIZED_LEDGER_ENTRY",
|
|
148
|
-
"HTTP_ARCHIVE_ERROR"
|
|
148
|
+
"HTTP_ARCHIVE_ERROR",
|
|
149
|
+
require_replayer.FUTURE_LEDGER_ENTRY_TIMESTAMP
|
|
149
150
|
]);
|
|
150
151
|
function sanitizeUntrustedWireToken(value, maxLen = 128) {
|
|
151
152
|
return String(value ?? "").replace(/[\r\n\t\x00-\x1f\x7f]+/g, " ").trim().slice(0, maxLen);
|
|
@@ -238,6 +239,8 @@ var FollowerSyncService = class {
|
|
|
238
239
|
this.stopped = false;
|
|
239
240
|
this.halted = false;
|
|
240
241
|
this.haltReason = null;
|
|
242
|
+
this.futureTimestampRejections = 0;
|
|
243
|
+
this.lastFutureTimestampRejection = null;
|
|
241
244
|
this.pendingCrashWindowReconcile = false;
|
|
242
245
|
this.initialCrashReconcileCompleted = false;
|
|
243
246
|
this.upstreamSequence = null;
|
|
@@ -254,7 +257,10 @@ var FollowerSyncService = class {
|
|
|
254
257
|
this.writePolicy = options.writePolicy;
|
|
255
258
|
this.syncMode = options.syncMode;
|
|
256
259
|
this.chainId = options.resolver.config.chainId || options.resolver.ledger.chainId;
|
|
257
|
-
this.replayer = new require_replayer.LedgerEntryReplayer(options.resolver
|
|
260
|
+
this.replayer = new require_replayer.LedgerEntryReplayer(options.resolver, options.futureTimestampGuard ? { futureTimestampGuard: {
|
|
261
|
+
...options.futureTimestampGuard,
|
|
262
|
+
onReject: (info) => this.recordFutureTimestampRejection(info)
|
|
263
|
+
} } : {});
|
|
258
264
|
const retentionMode = options.retentionMode ?? "archive";
|
|
259
265
|
if (retentionMode !== "archive" && retentionMode !== "tiered") throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid retentionMode "${String(retentionMode)}": expected "archive" or "tiered"`);
|
|
260
266
|
if (retentionMode === "tiered" && !options.coldArchiveStore) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "FollowerSyncService with retentionMode=\"tiered\" requires coldArchiveStore");
|
|
@@ -531,6 +537,17 @@ var FollowerSyncService = class {
|
|
|
531
537
|
if (liveCommit && liveCommit !== "UNKNOWN" && liveCommit !== "GENESIS") return liveCommit;
|
|
532
538
|
return localCp?.stateRoot ?? null;
|
|
533
539
|
}
|
|
540
|
+
recordFutureTimestampRejection(info) {
|
|
541
|
+
this.futureTimestampRejections++;
|
|
542
|
+
this.lastFutureTimestampRejection = { ...info };
|
|
543
|
+
}
|
|
544
|
+
/** #1961: how many peer entries were refused for a future timestamp, and the last one (for alerting/tests). */
|
|
545
|
+
getFutureTimestampRejections() {
|
|
546
|
+
return {
|
|
547
|
+
count: this.futureTimestampRejections,
|
|
548
|
+
last: this.lastFutureTimestampRejection ? { ...this.lastFutureTimestampRejection } : null
|
|
549
|
+
};
|
|
550
|
+
}
|
|
534
551
|
async getFollowerStatus() {
|
|
535
552
|
const [localSequence, latestCp, localStateCommitHash, synced] = await Promise.all([
|
|
536
553
|
this.resolver.ledger.getLatestSequence(),
|
|
@@ -1519,7 +1536,7 @@ var FollowerSyncService = class {
|
|
|
1519
1536
|
if (entry.finalized !== true) throw new _ocap_util_lib_error.CustomError("UNFINALIZED_LEDGER_ENTRY", `Hot-tail entry seq=${entry.sequence} is not finalized`);
|
|
1520
1537
|
if (!Number.isSafeInteger(entry.timestamp) || entry.timestamp < 0 || entry.timestamp > MAX_SAFE_EPOCH_MS) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Hot-tail entry seq=${entry.sequence} has invalid timestamp: ${String(entry.timestamp)}`);
|
|
1521
1538
|
if (typeof entry.txRaw !== "string" || !entry.txRaw || entry.txRaw !== entry.txRaw.trim()) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Hot-tail entry seq=${entry.sequence} has missing or non-canonical txRaw`);
|
|
1522
|
-
this.replayer.validateWireEntry(entry);
|
|
1539
|
+
this.replayer.validateWireEntry(entry, { skipFutureTimestampCheck: true });
|
|
1523
1540
|
const expectedHash = (0, _arcblock_ledger_core.computeEntryHash)(entry.sequence, entry.txRaw, entry.stateCommitHash ?? "", entry.sequence >= v2Cutoff ? 2 : 1);
|
|
1524
1541
|
if (entry.entryHash !== expectedHash) throw new _ocap_util_lib_error.CustomError("LEDGER_DIVERGENCE", `Hot-tail entryHash mismatch at seq=${entry.sequence}: expected ${expectedHash}, got ${entry.entryHash}`);
|
|
1525
1542
|
entryHashes.push(entry.entryHash);
|
|
@@ -1547,6 +1564,7 @@ var FollowerSyncService = class {
|
|
|
1547
1564
|
signatureRatchetLocked: true
|
|
1548
1565
|
});
|
|
1549
1566
|
}
|
|
1567
|
+
for (const entry of entries) this.replayer.assertEntryTimestampNotInFuture(entry);
|
|
1550
1568
|
return batchParsedV2From;
|
|
1551
1569
|
}
|
|
1552
1570
|
const cp = upstreamStatus.latestCheckpoint;
|
|
@@ -1570,11 +1588,15 @@ var FollowerSyncService = class {
|
|
|
1570
1588
|
signatureRatchetLocked: true
|
|
1571
1589
|
});
|
|
1572
1590
|
}
|
|
1591
|
+
for (const entry of entries) this.replayer.assertEntryTimestampNotInFuture(entry);
|
|
1573
1592
|
return;
|
|
1574
1593
|
}
|
|
1575
1594
|
}
|
|
1576
1595
|
}
|
|
1577
|
-
if (importOpts.allowUnauthenticated && !entriesBody.batchSignature && !this.hotstuffClusterConfig)
|
|
1596
|
+
if (importOpts.allowUnauthenticated && !entriesBody.batchSignature && !this.hotstuffClusterConfig) {
|
|
1597
|
+
for (const entry of entries) this.replayer.assertEntryTimestampNotInFuture(entry);
|
|
1598
|
+
return batchParsedV2From ?? parsedV2From;
|
|
1599
|
+
}
|
|
1578
1600
|
throw new _ocap_util_lib_error.CustomError("HOT_TAIL_SIGNATURE_MISSING", "Hot-tail /api/ledger/entries response is missing a valid proposer batchSignature");
|
|
1579
1601
|
}
|
|
1580
1602
|
/**
|
|
@@ -1779,7 +1801,7 @@ var FollowerSyncService = class {
|
|
|
1779
1801
|
for (const item of batch) {
|
|
1780
1802
|
if (item.sequence > targetCp.sequence) break;
|
|
1781
1803
|
if (item.sequence !== cursor) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Non-contiguous entry sequence at height ${nextHeight}: expected ${cursor}, got ${item.sequence}`);
|
|
1782
|
-
this.replayer.validateWireEntry(item);
|
|
1804
|
+
this.replayer.validateWireEntry(item, { skipFutureTimestampCheck: true });
|
|
1783
1805
|
segmentEntries.push(item);
|
|
1784
1806
|
cursor++;
|
|
1785
1807
|
}
|
|
@@ -1802,6 +1824,7 @@ var FollowerSyncService = class {
|
|
|
1802
1824
|
requireSignature: !importOpts.allowUnauthenticated,
|
|
1803
1825
|
allowUnauthenticated: importOpts.allowUnauthenticated
|
|
1804
1826
|
});
|
|
1827
|
+
for (const item of segmentEntries) this.replayer.assertEntryTimestampNotInFuture(item);
|
|
1805
1828
|
let mutatedLocalDb = false;
|
|
1806
1829
|
try {
|
|
1807
1830
|
if (segmentEntries.length > 0 && typeof this.resolver.statedb.runWithinDryRunSession === "function") {
|
|
@@ -1892,7 +1915,7 @@ var FollowerSyncService = class {
|
|
|
1892
1915
|
}
|
|
1893
1916
|
async replayCrashWindowEntry(entry) {
|
|
1894
1917
|
try {
|
|
1895
|
-
this.replayer.validateWireEntry(entry);
|
|
1918
|
+
this.replayer.validateWireEntry(entry, { skipFutureTimestampCheck: true });
|
|
1896
1919
|
const expectedCommit = (entry.stateCommitHash ?? "").trim();
|
|
1897
1920
|
const v2Cutoff = typeof this.resolver.ledger.getEntryHashV2From === "function" ? this.resolver.ledger.getEntryHashV2From() : void 0;
|
|
1898
1921
|
if (typeof v2Cutoff === "number" && !Number.isNaN(v2Cutoff)) {
|
|
@@ -2025,7 +2048,8 @@ var FollowerSyncService = class {
|
|
|
2025
2048
|
if (!matchedBase && unappliedOrdered.length > 0 && unappliedOrdered[0].sequence === expectedDryRunPrevSeq + 1 && typeof this.resolver.statedb.runWithinDryRunSession === "function") {
|
|
2026
2049
|
const dryRun = await this.replayer.dryRunVerifyEntries(unappliedOrdered, {
|
|
2027
2050
|
expectedPrevSequence: expectedDryRunPrevSeq,
|
|
2028
|
-
prevStateRoot: currentCommit
|
|
2051
|
+
prevStateRoot: currentCommit,
|
|
2052
|
+
skipFutureTimestampCheck: true
|
|
2029
2053
|
}).catch((dryErr) => {
|
|
2030
2054
|
if (isTransientSqliteLockError(dryErr)) throw dryErr;
|
|
2031
2055
|
return null;
|
|
@@ -2381,7 +2405,13 @@ var FollowerSyncService = class {
|
|
|
2381
2405
|
this.haltFailClosed(haltReason, errCode);
|
|
2382
2406
|
throw err;
|
|
2383
2407
|
}
|
|
2384
|
-
this.resolver.logger.
|
|
2408
|
+
if (errCode === require_replayer.FUTURE_LEDGER_ENTRY_TIMESTAMP) this.resolver.logger.error(`FollowerSyncService refused a future-dated ledger entry (${errCode}); will retry`, {
|
|
2409
|
+
chainId: this.chainId,
|
|
2410
|
+
code: errCode,
|
|
2411
|
+
rejections: this.futureTimestampRejections,
|
|
2412
|
+
error: err instanceof Error ? err.message : String(err)
|
|
2413
|
+
});
|
|
2414
|
+
else this.resolver.logger.warn("FollowerSyncService transient sync error", {
|
|
2385
2415
|
chainId: this.chainId,
|
|
2386
2416
|
error: err instanceof Error ? err.message : String(err)
|
|
2387
2417
|
});
|
package/lib/follower.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DnsLookupAllFn } from "./node-preferences.cjs";
|
|
2
|
-
import { IReplayerResolverTarget, LedgerEntryReplayer } from "./replayer.cjs";
|
|
2
|
+
import { IFutureTimestampRejection, IReplayerResolverTarget, LedgerEntryReplayer } from "./replayer.cjs";
|
|
3
3
|
import { IFollowerStatusResponse, IHotStuffClusterConfig, ILedgerArchiveHead, ILedgerSegment, INodeRuntimeAdapter, IResolverContext, TFollowerSyncMode, TNodeRetentionMode, TNodeRole, TNodeWritePolicy } from "@ocap/types";
|
|
4
4
|
import { ICheckpointSignerWallet } from "@arcblock/ledger-core";
|
|
5
5
|
|
|
@@ -90,6 +90,15 @@ interface FollowerSyncServiceOptions {
|
|
|
90
90
|
fetchImpl?: typeof fetch;
|
|
91
91
|
dnsLookup?: DnsLookupAllFn;
|
|
92
92
|
env?: Record<string, string | undefined>;
|
|
93
|
+
/**
|
|
94
|
+
* #1961: refuse (retryably) peer entries with `sequence >= activationSequence` whose timestamp is more than
|
|
95
|
+
* `maxSkewMs` ahead of `now()`. Unset (default): no guard, today's behavior.
|
|
96
|
+
*/
|
|
97
|
+
futureTimestampGuard?: {
|
|
98
|
+
activationSequence: number;
|
|
99
|
+
maxSkewMs: number;
|
|
100
|
+
now?: () => number;
|
|
101
|
+
};
|
|
93
102
|
}
|
|
94
103
|
declare function isTransientSqliteLockError(err: unknown): boolean;
|
|
95
104
|
declare class FollowerSyncService implements INodeRuntimeAdapter {
|
|
@@ -129,6 +138,8 @@ declare class FollowerSyncService implements INodeRuntimeAdapter {
|
|
|
129
138
|
private stopped;
|
|
130
139
|
private halted;
|
|
131
140
|
private haltReason;
|
|
141
|
+
private futureTimestampRejections;
|
|
142
|
+
private lastFutureTimestampRejection;
|
|
132
143
|
private pendingCrashWindowReconcile;
|
|
133
144
|
private initialCrashReconcileCompleted;
|
|
134
145
|
private upstreamSequence;
|
|
@@ -185,6 +196,12 @@ declare class FollowerSyncService implements INodeRuntimeAdapter {
|
|
|
185
196
|
* reading untrusted upstream `segmentEntries` (#1711).
|
|
186
197
|
*/
|
|
187
198
|
private resolveLocalFraudAlertStateRoot;
|
|
199
|
+
private recordFutureTimestampRejection;
|
|
200
|
+
/** #1961: how many peer entries were refused for a future timestamp, and the last one (for alerting/tests). */
|
|
201
|
+
getFutureTimestampRejections(): {
|
|
202
|
+
count: number;
|
|
203
|
+
last: IFutureTimestampRejection | null;
|
|
204
|
+
};
|
|
188
205
|
getFollowerStatus(): Promise<IFollowerStatusResponse>;
|
|
189
206
|
private isAllowedHotStuffValidator;
|
|
190
207
|
private hasCommittedTrustAnchor;
|
package/lib/hooks.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_package = require('./package.cjs');
|
|
3
3
|
let _ocap_util = require("@ocap/util");
|
|
4
|
+
let lodash_merge = require("lodash/merge");
|
|
5
|
+
lodash_merge = require_rolldown_runtime.__toESM(lodash_merge);
|
|
4
6
|
let _arcblock_did_util = require("@arcblock/did-util");
|
|
5
7
|
let debug = require("debug");
|
|
6
8
|
debug = require_rolldown_runtime.__toESM(debug);
|
|
7
|
-
let lodash_merge = require("lodash/merge");
|
|
8
|
-
lodash_merge = require_rolldown_runtime.__toESM(lodash_merge);
|
|
9
9
|
let lodash_pick = require("lodash/pick");
|
|
10
10
|
lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
|
|
11
11
|
|
package/lib/index.cjs
CHANGED
|
@@ -21,6 +21,8 @@ let _ocap_util = require("@ocap/util");
|
|
|
21
21
|
let _ocap_util_lib_error = require("@ocap/util/lib/error");
|
|
22
22
|
let _ocap_state = require("@ocap/state");
|
|
23
23
|
_ocap_state = require_rolldown_runtime.__toESM(_ocap_state);
|
|
24
|
+
let lodash_cloneDeep = require("lodash/cloneDeep");
|
|
25
|
+
lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
|
|
24
26
|
let _arcblock_did_util = require("@arcblock/did-util");
|
|
25
27
|
let debug = require("debug");
|
|
26
28
|
debug = require_rolldown_runtime.__toESM(debug);
|
|
@@ -35,8 +37,6 @@ let _ocap_tx_protocols_lib_util = require("@ocap/tx-protocols/lib/util");
|
|
|
35
37
|
let _ocap_util_lib_constant = require("@ocap/util/lib/constant");
|
|
36
38
|
let _ocap_util_lib_deposit_v2_bridge_fields = require("@ocap/util/lib/deposit-v2-bridge-fields");
|
|
37
39
|
let _ocap_util_lib_md5 = require("@ocap/util/lib/md5");
|
|
38
|
-
let lodash_cloneDeep = require("lodash/cloneDeep");
|
|
39
|
-
lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
|
|
40
40
|
let lodash_get = require("lodash/get");
|
|
41
41
|
lodash_get = require_rolldown_runtime.__toESM(lodash_get);
|
|
42
42
|
let lodash_isEmpty = require("lodash/isEmpty");
|
|
@@ -2672,6 +2672,7 @@ exports.ConsensusAbortError = require_hotstuff_runtime.ConsensusAbortError;
|
|
|
2672
2672
|
exports.DEFAULT_FOLLOWER_MAX_SYNC_LAG = require_follower.DEFAULT_FOLLOWER_MAX_SYNC_LAG;
|
|
2673
2673
|
exports.DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS = require_follower.DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS;
|
|
2674
2674
|
exports.DEFAULT_FOLLOWER_POLL_INTERVAL_MS = require_follower.DEFAULT_FOLLOWER_POLL_INTERVAL_MS;
|
|
2675
|
+
exports.FUTURE_LEDGER_ENTRY_TIMESTAMP = require_replayer.FUTURE_LEDGER_ENTRY_TIMESTAMP;
|
|
2675
2676
|
exports.FollowerSyncService = require_follower.FollowerSyncService;
|
|
2676
2677
|
exports.GRAPHQL_INDEXED_TX_COLUMNS = GRAPHQL_INDEXED_TX_COLUMNS;
|
|
2677
2678
|
exports.HotStuffNodeRuntime = require_hotstuff_runtime.HotStuffNodeRuntime;
|
package/lib/index.d.cts
CHANGED
|
@@ -3,7 +3,7 @@ import { CreateNodeDashboardRouterOptions, CreateUnifiedConsoleMiddlewareOptions
|
|
|
3
3
|
import { IAddressArgs, IAssetState, IChainConfig, IChunkIterator, IDataObject, IDelegateState, IEvidenceState, IFilter as IFilter$1, IFollowerStatusResponse, IGetAccountStateArgs, IGetAccountTokensArgs, IGetStateParams, IIndexDB as IIndexDB$1, IListChunksParams, INodeRuntimeAdapter, IPaginatedResult, IPipelineLogger as IPipelineLogger$1, IResolver, IResolverAccountState, IResolverChainInfo, IResolverContext as IResolverContext$1, IResolverFactoryState, IResolverForgeStats, IResolverListAccountsResult, IResolverListAssetsResult, IResolverListDelegationsResult, IResolverListFactoriesResult, IResolverListRollupBlocksResult, IResolverListRollupValidatorsResult, IResolverListRollupsResult, IResolverListStakesResult, IResolverListTokenFactoriesResult, IResolverListTokensResult, IResolverListTransactionsResult, IResolverNetInfo, IResolverNodeInfo, IResolverPaging, IResolverParams, IResolverRollupState, IResolverStakeState, IResolverTransaction, IResolverValidatorsInfo, IRollupBlock, IStateDB as IStateDB$1, ITokenCache, ITokenFactoryState, ITokenFlowsResult, ITokenInfo, ITokenState, TIndexedTokenState as TIndexedTokenState$1, TRequestEstimateGas, TRequestGetEvidenceState, TRequestGetRollupBlock, TRequestGetTokenDistribution, TRequestGetTx, TRequestListAssetTransactions, TRequestListAssets, TRequestListDelegations, TRequestListFactories, TRequestListRollupBlocks, TRequestListRollupValidators, TRequestListRollups, TRequestListStakes, TRequestListTokenFactories, TRequestListTokenFlows, TRequestListTokens, TRequestListTopAccounts, TRequestListTransactions, TRequestSearch, TRequestVerifyAccountRisk, TSearchResult, TTokenDistribution, TVerifyAccountRiskResult } from "./types.cjs";
|
|
4
4
|
import { CreateAPIHandlerOptions, ICreateAPIHandlerParams } from "./api.cjs";
|
|
5
5
|
import { CreateExplorerMiddlewareOptions, createExplorerMiddleware, isExplorerEnabled } from "./explorer.cjs";
|
|
6
|
-
import { IDryRunVerifyEntriesOptions, IDryRunVerifyEntriesResult, IReplayEntryOptions, IReplayEntryResult, IReplayerResolverTarget, LedgerEntryReplayer } from "./replayer.cjs";
|
|
6
|
+
import { FUTURE_LEDGER_ENTRY_TIMESTAMP, IDryRunVerifyEntriesOptions, IDryRunVerifyEntriesResult, IFutureTimestampGuardOptions, IFutureTimestampRejection, ILedgerEntryReplayerOptions, IReplayEntryOptions, IReplayEntryResult, IReplayerResolverTarget, IValidateWireEntryOptions, LedgerEntryReplayer } from "./replayer.cjs";
|
|
7
7
|
import { DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, FollowerSyncServiceOptions, IColdSegmentReader, ILeaderRouterLike, TFollowerUpstreamFetchInterceptor, TFollowerUpstreamFetchKind, isTransientSqliteLockError } from "./follower.cjs";
|
|
8
8
|
import { ConsensusAbortError, HotStuffNodeRuntime, HotStuffNodeRuntimeOptions, IHotStuffNetworkInterceptorContext, IHotStuffRuntimeStateSnapshot, IHotStuffRuntimeStateStore, TConsensusAbortCode } from "./hotstuff-runtime.cjs";
|
|
9
9
|
import { MigrationChainManager } from "./migration-chain.cjs";
|
|
@@ -350,4 +350,4 @@ declare class OCAPResolver implements IResolver {
|
|
|
350
350
|
}): Promise<IChunkIterator<IResolverStakeState>>;
|
|
351
351
|
}
|
|
352
352
|
//#endregion
|
|
353
|
-
export { type AdminAuthGuardOptions, ConsensusAbortError, type CreateAPIHandlerOptions, type CreateExplorerMiddlewareOptions, type CreateNodeDashboardRouterOptions, type CreateUnifiedConsoleMiddlewareOptions, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, type DnsLookupAllFn, FollowerSyncService, type FollowerSyncServiceOptions, GRAPHQL_INDEXED_TX_COLUMNS, HotStuffNodeRuntime, type HotStuffNodeRuntimeOptions, type IAdminAuthGuard, type IAttributedBlockedAccount, type IAttributedReservedSymbol, type IAttributedTrustedAccount, type IBlockedAccountEntry, type IChainConfig, type IChunkIterator, type IColdSegmentReader, type ICreateAPIHandlerParams, type IDashboardResolverTarget, type IDataObject, type IDatabaseFileMetrics, type IDryRunVerifyEntriesOptions, type IDryRunVerifyEntriesResult, type IFollowerStatusResponse, type IHotStuffNetworkInterceptorContext, type IHotStuffRuntimeStateSnapshot, type IHotStuffRuntimeStateStore, type ILeaderRouterLike, type ILedgerHealthSummary, type ILedgerHealthThresholds, type ILegacyPreferencesResult, type INodeMaintenanceController, type INodeMaintenanceStatusSummary, type INodePreferencesFileSchema, type INodePreferencesSnapshot, type INodeRuntimeAdapter, type INodeRuntimePreferences, type IPaginatedResult, type IReplayEntryOptions, type IReplayEntryResult, type IReplayerResolverTarget, type IReservedSymbolEntry, type IResolverPaging, type IResolverParams, type IResolverTransaction, type ISlowStorageTelemetry, type ITokenInfo, type ITrustedAccountEntry, type IUpdateNodePreferencesInput, type IUpdateNodePreferencesResult, LedgerEntryReplayer, MAX_BLOCKED_ACCOUNTS, MAX_CONFIG_BODY_BYTES, MAX_MEMO_LENGTH, MAX_PEER_URLS, MAX_RESERVED_SYMBOLS, MAX_TRUSTED_ACCOUNTS, type NodeMaintenanceControllerOptions, NodePreferencesError, NodePreferencesManager, type NodePreferencesManagerOptions, type TConsensusAbortCode, type TFollowerUpstreamFetchInterceptor, type TFollowerUpstreamFetchKind, type TPreferenceSource, UNIFIED_CONSOLE_APP_JS, applyBootRuntimePreferences, buildUnifiedConsoleHtml, collectLedgerHealthSummary, createAdminAuthGuard, createExplorerMiddleware, createFollowerPeerFetchGuard, createNodeDashboardRouter, createNodeMaintenanceController, createUnifiedConsoleMiddleware, OCAPResolver as default, formatData, formatDelegationOps, isDashboardEnabled, isExplorerEnabled, isPrivateOrReservedIpAddress, isTransientSqliteLockError, isValidAccountAddressCandidate, loadNodePreferences, normalizeBlockedAccountKey, timingSafeTokenEqual, validateFollowerPeerUrls };
|
|
353
|
+
export { type AdminAuthGuardOptions, ConsensusAbortError, type CreateAPIHandlerOptions, type CreateExplorerMiddlewareOptions, type CreateNodeDashboardRouterOptions, type CreateUnifiedConsoleMiddlewareOptions, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, type DnsLookupAllFn, FUTURE_LEDGER_ENTRY_TIMESTAMP, FollowerSyncService, type FollowerSyncServiceOptions, GRAPHQL_INDEXED_TX_COLUMNS, HotStuffNodeRuntime, type HotStuffNodeRuntimeOptions, type IAdminAuthGuard, type IAttributedBlockedAccount, type IAttributedReservedSymbol, type IAttributedTrustedAccount, type IBlockedAccountEntry, type IChainConfig, type IChunkIterator, type IColdSegmentReader, type ICreateAPIHandlerParams, type IDashboardResolverTarget, type IDataObject, type IDatabaseFileMetrics, type IDryRunVerifyEntriesOptions, type IDryRunVerifyEntriesResult, type IFollowerStatusResponse, type IFutureTimestampGuardOptions, type IFutureTimestampRejection, type IHotStuffNetworkInterceptorContext, type IHotStuffRuntimeStateSnapshot, type IHotStuffRuntimeStateStore, type ILeaderRouterLike, type ILedgerEntryReplayerOptions, type ILedgerHealthSummary, type ILedgerHealthThresholds, type ILegacyPreferencesResult, type INodeMaintenanceController, type INodeMaintenanceStatusSummary, type INodePreferencesFileSchema, type INodePreferencesSnapshot, type INodeRuntimeAdapter, type INodeRuntimePreferences, type IPaginatedResult, type IReplayEntryOptions, type IReplayEntryResult, type IReplayerResolverTarget, type IReservedSymbolEntry, type IResolverPaging, type IResolverParams, type IResolverTransaction, type ISlowStorageTelemetry, type ITokenInfo, type ITrustedAccountEntry, type IUpdateNodePreferencesInput, type IUpdateNodePreferencesResult, type IValidateWireEntryOptions, LedgerEntryReplayer, MAX_BLOCKED_ACCOUNTS, MAX_CONFIG_BODY_BYTES, MAX_MEMO_LENGTH, MAX_PEER_URLS, MAX_RESERVED_SYMBOLS, MAX_TRUSTED_ACCOUNTS, type NodeMaintenanceControllerOptions, NodePreferencesError, NodePreferencesManager, type NodePreferencesManagerOptions, type TConsensusAbortCode, type TFollowerUpstreamFetchInterceptor, type TFollowerUpstreamFetchKind, type TPreferenceSource, UNIFIED_CONSOLE_APP_JS, applyBootRuntimePreferences, buildUnifiedConsoleHtml, collectLedgerHealthSummary, createAdminAuthGuard, createExplorerMiddleware, createFollowerPeerFetchGuard, createNodeDashboardRouter, createNodeMaintenanceController, createUnifiedConsoleMiddleware, OCAPResolver as default, formatData, formatDelegationOps, isDashboardEnabled, isExplorerEnabled, isPrivateOrReservedIpAddress, isTransientSqliteLockError, isValidAccountAddressCandidate, loadNodePreferences, normalizeBlockedAccountKey, timingSafeTokenEqual, validateFollowerPeerUrls };
|
package/lib/node-preferences.cjs
CHANGED
|
@@ -832,8 +832,9 @@ var NodePreferencesManager = class {
|
|
|
832
832
|
* socket address alone would put all clients in one bucket; `resolveClientIp` reads the trusted proxy header
|
|
833
833
|
* (`CHAIN_CLIENT_IP_HEADERS`, default `x-real-ip`) only from a loopback peer and ignores them from a remote one (#1922, trust rule in `@ocap/util/lib/client-ip`).
|
|
834
834
|
*/
|
|
835
|
-
function extractClientIp(req) {
|
|
836
|
-
|
|
835
|
+
function extractClientIp(req, env) {
|
|
836
|
+
const headers = env !== void 0 ? (0, _ocap_util_lib_client_ip.getTrustedClientIpHeaders)(env.CHAIN_CLIENT_IP_HEADERS) : void 0;
|
|
837
|
+
return (0, _ocap_util_lib_client_ip.resolveClientIp)(req, headers !== void 0 ? { headers } : void 0) || "unknown";
|
|
837
838
|
}
|
|
838
839
|
function extractProvidedAdminToken(req) {
|
|
839
840
|
const headers = req.headers || {};
|
|
@@ -925,7 +926,7 @@ function createAdminAuthGuard(options = {}) {
|
|
|
925
926
|
const isGatewayNonAdminBearerOnly = Boolean(req.user) && !hasAdminSpecificHeader;
|
|
926
927
|
if (hasExplicitAuthHeader && !isGatewayNonAdminBearerOnly) {
|
|
927
928
|
const now = Date.now();
|
|
928
|
-
const ip = extractClientIp(req);
|
|
929
|
+
const ip = extractClientIp(req, env);
|
|
929
930
|
if (!isRateLimited(ip, now).limited) recordFailure(ip, now);
|
|
930
931
|
}
|
|
931
932
|
return false;
|
|
@@ -939,7 +940,7 @@ function createAdminAuthGuard(options = {}) {
|
|
|
939
940
|
if (timingSafeTokenEqual(expected, token)) return "admin";
|
|
940
941
|
if (Boolean(req.user) && !hasAdminSpecificHeader) return "anonymous";
|
|
941
942
|
const now = Date.now();
|
|
942
|
-
const ip = extractClientIp(req);
|
|
943
|
+
const ip = extractClientIp(req, env);
|
|
943
944
|
const rate = isRateLimited(ip, now);
|
|
944
945
|
if (rate.limited) {
|
|
945
946
|
res.setHeader("Retry-After", String(rate.retryAfterSec));
|
|
@@ -999,7 +1000,7 @@ function createAdminAuthGuard(options = {}) {
|
|
|
999
1000
|
return;
|
|
1000
1001
|
}
|
|
1001
1002
|
const now = Date.now();
|
|
1002
|
-
const ip = extractClientIp(req);
|
|
1003
|
+
const ip = extractClientIp(req, env);
|
|
1003
1004
|
const rate = isRateLimited(ip, now);
|
|
1004
1005
|
if (rate.limited) {
|
|
1005
1006
|
res.setHeader("Retry-After", String(rate.retryAfterSec));
|