@ocap/resolver 1.31.9 → 1.32.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/_virtual/rolldown_runtime.mjs +7 -0
- package/esm/api.d.mts +33 -5
- package/esm/api.mjs +939 -53
- package/esm/dashboard.d.mts +199 -0
- package/esm/dashboard.mjs +2481 -0
- package/esm/explorer.d.mts +29 -0
- package/esm/explorer.mjs +227 -0
- package/esm/follower.d.mts +294 -0
- package/esm/follower.mjs +2452 -0
- package/esm/hooks.mjs +1 -1
- package/esm/hotstuff-runtime.d.mts +271 -0
- package/esm/hotstuff-runtime.mjs +2668 -0
- package/esm/index.d.mts +79 -4
- package/esm/index.mjs +911 -174
- package/esm/node-preferences.d.mts +203 -0
- package/esm/node-preferences.mjs +1021 -0
- package/esm/replayer.d.mts +114 -0
- package/esm/replayer.mjs +430 -0
- package/esm/token-distribution.mjs +2 -2
- package/esm/token-flow.mjs +1 -1
- package/esm/types.d.mts +25 -2
- package/lib/api.cjs +941 -52
- package/lib/api.d.cts +33 -5
- package/lib/dashboard.cjs +2491 -0
- package/lib/dashboard.d.cts +199 -0
- package/lib/explorer.cjs +227 -0
- package/lib/explorer.d.cts +29 -0
- package/lib/follower.cjs +2458 -0
- package/lib/follower.d.cts +294 -0
- package/lib/hooks.cjs +1 -1
- package/lib/hotstuff-runtime.cjs +2671 -0
- package/lib/hotstuff-runtime.d.cts +271 -0
- package/lib/index.cjs +946 -174
- package/lib/index.d.cts +79 -4
- package/lib/node-preferences.cjs +1043 -0
- package/lib/node-preferences.d.cts +203 -0
- package/lib/replayer.cjs +432 -0
- package/lib/replayer.d.cts +114 -0
- package/lib/token-distribution.cjs +2 -2
- package/lib/token-flow.cjs +1 -1
- package/lib/types.d.cts +25 -2
- package/package.json +20 -14
|
@@ -0,0 +1,2481 @@
|
|
|
1
|
+
import { MAX_CONFIG_BODY_BYTES, NodePreferencesError, createAdminAuthGuard } from "./node-preferences.mjs";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as os from "node:os";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { getGasSecuritySummary } from "@ocap/tx-protocols";
|
|
6
|
+
|
|
7
|
+
//#region src/dashboard.ts
|
|
8
|
+
/**
|
|
9
|
+
* Chain Node Status Dashboard, Network Health Telemetry, Auxiliary Config API,
|
|
10
|
+
* Maintenance Action Controller & Unified Console UI (#1756)
|
|
11
|
+
*
|
|
12
|
+
* Architectural & Security Invariants:
|
|
13
|
+
* 1. Two-tier TTL caching (`1,000 ms` fast runtime/health tier + `15,000 ms` slow SQLite `count()`
|
|
14
|
+
* and `fs.promises.stat` tier) with single-flight promise coalescing prevents RPC/I/O DoS.
|
|
15
|
+
* 2. Unauthenticated split-plane redaction: private consensus wire endpoints, Follower upstream URLs,
|
|
16
|
+
* and host filesystem paths are NEVER exposed without valid admin authentication.
|
|
17
|
+
* 3. Pre-queue admission isolation: `blockedAccounts` updates apply at RPC admission + `/blocked`
|
|
18
|
+
* without mutating consensus `stateCommitHash` on HotStuff replicas or Followers.
|
|
19
|
+
* 4. Strict CSP (`script-src 'self'; object-src 'none'; frame-ancestors 'none'`), `sessionStorage`-only
|
|
20
|
+
* admin token, and `textContent`-only DOM rendering eliminate XSS / Clickjacking / CSRF vectors.
|
|
21
|
+
*/
|
|
22
|
+
const FAST_DASHBOARD_TTL_MS = 1e3;
|
|
23
|
+
const SLOW_STORAGE_TTL_MS = 15e3;
|
|
24
|
+
const SYNC_NOW_COOLDOWN_MS = 5e3;
|
|
25
|
+
const MAX_ACTION_BODY_BYTES = 8 * 1024;
|
|
26
|
+
function formatDurationCompact(ms) {
|
|
27
|
+
if (ms == null) return null;
|
|
28
|
+
const s = Math.max(0, Math.floor(ms / 1e3));
|
|
29
|
+
const d = Math.floor(s / 86400);
|
|
30
|
+
const h = Math.floor(s % 86400 / 3600);
|
|
31
|
+
const m = Math.floor(s % 3600 / 60);
|
|
32
|
+
const sec = s % 60;
|
|
33
|
+
const parts = [];
|
|
34
|
+
if (d) parts.push(`${d}d`);
|
|
35
|
+
if (h) parts.push(`${h}h`);
|
|
36
|
+
if (m) parts.push(`${m}m`);
|
|
37
|
+
if (sec || parts.length === 0) parts.push(`${sec}s`);
|
|
38
|
+
return parts.join(" ");
|
|
39
|
+
}
|
|
40
|
+
function resolveRetentionModeFromEnv(explicit, env = process.env) {
|
|
41
|
+
if (explicit === "tiered" || explicit === "archive") return explicit;
|
|
42
|
+
return String(env.CHAIN_RETENTION || "").trim().toLowerCase() === "tiered" ? "tiered" : "archive";
|
|
43
|
+
}
|
|
44
|
+
function resolveSafeSnapshotBaseUrl(env = process.env) {
|
|
45
|
+
const raw = String(env.LEDGER_SNAPSHOT_BASE_URL || "").trim();
|
|
46
|
+
if (!raw) return null;
|
|
47
|
+
try {
|
|
48
|
+
const parsed = new URL(raw);
|
|
49
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
50
|
+
parsed.username = "";
|
|
51
|
+
parsed.password = "";
|
|
52
|
+
parsed.search = "";
|
|
53
|
+
parsed.hash = "";
|
|
54
|
+
return parsed.toString().replace(/\/+$/g, "");
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async function collectLedgerHealthSummary(options) {
|
|
60
|
+
const env = options.env ?? process.env;
|
|
61
|
+
const extLedger = options.ledger;
|
|
62
|
+
const halted = Boolean(options.runtime?.isHalted?.());
|
|
63
|
+
const reconciling = !halted && Boolean(options.runtime?.isReconciling?.());
|
|
64
|
+
const haltReason = halted ? options.runtime?.getHaltReason?.() ?? null : null;
|
|
65
|
+
const health = await options.ledger.getHealth();
|
|
66
|
+
const lagThreshold = Number(options.thresholds?.checkpointLag) || Number(env.LEDGER_HEALTH_LAG_THRESHOLD) || 1e3;
|
|
67
|
+
const ageThresholdMs = Number(options.thresholds?.checkpointAgeMs) || Number(env.LEDGER_HEALTH_AGE_THRESHOLD_MS) || 36e5;
|
|
68
|
+
const unfinalizedAgeThresholdMs = Number(options.thresholds?.unfinalizedAgeMs) || Number(env.LEDGER_HEALTH_UNFINALIZED_AGE_THRESHOLD_MS) || 3e5;
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
const oldestUnfinalizedAgeMs = health.oldestUnfinalizedTimestamp ? now - health.oldestUnfinalizedTimestamp : null;
|
|
71
|
+
const lagViolation = health.checkpointLag > lagThreshold;
|
|
72
|
+
const ageViolation = lagViolation && health.checkpointAgeMs != null && health.checkpointAgeMs > ageThresholdMs;
|
|
73
|
+
const unfinalizedViolation = oldestUnfinalizedAgeMs != null && oldestUnfinalizedAgeMs > unfinalizedAgeThresholdMs;
|
|
74
|
+
const healthy = !halted && !reconciling && !lagViolation && !ageViolation && !unfinalizedViolation;
|
|
75
|
+
const toIso = (ts) => ts ? new Date(ts).toISOString() : null;
|
|
76
|
+
const rawV2From = typeof options.ledger.getEntryHashV2From === "function" ? options.ledger.getEntryHashV2From() : void 0;
|
|
77
|
+
const entryHashV2From = rawV2From === void 0 ? null : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
|
|
78
|
+
const proposer = options.ledger.getProposer?.() || null;
|
|
79
|
+
const proposerPublicKey = options.ledger.getProposerPublicKey?.() || null;
|
|
80
|
+
const checkpointSigningEnabled = typeof options.ledger.isCheckpointSigningEnabled === "function" ? options.ledger.isCheckpointSigningEnabled() : Boolean(proposerPublicKey);
|
|
81
|
+
const witnessRegistry = extLedger.getWitnessRegistry?.();
|
|
82
|
+
return {
|
|
83
|
+
healthy,
|
|
84
|
+
...halted ? {
|
|
85
|
+
halted: true,
|
|
86
|
+
code: "NODE_HALTED",
|
|
87
|
+
haltReason,
|
|
88
|
+
error: haltReason || "Chain node is halted fail-closed"
|
|
89
|
+
} : {},
|
|
90
|
+
...reconciling ? {
|
|
91
|
+
halted: false,
|
|
92
|
+
reconciling: true,
|
|
93
|
+
code: "FOLLOWER_RECONCILING",
|
|
94
|
+
error: "Follower is reconciling local statedb with imported ledger segment"
|
|
95
|
+
} : {},
|
|
96
|
+
proposer,
|
|
97
|
+
proposerPublicKey,
|
|
98
|
+
checkpointSigningEnabled,
|
|
99
|
+
retentionMode: resolveRetentionModeFromEnv(options.retentionMode, env),
|
|
100
|
+
witnessQuorum: witnessRegistry?.getQuorum() ?? 0,
|
|
101
|
+
witnessCircuitBroken: witnessRegistry?.isCircuitBroken() ?? false,
|
|
102
|
+
witnessFraudAlertCount: witnessRegistry?.getFraudAlerts().length ?? 0,
|
|
103
|
+
entryHashV2From,
|
|
104
|
+
latestSequence: health.latestSequence,
|
|
105
|
+
latestCheckpoint: health.latestCheckpoint ? {
|
|
106
|
+
...health.latestCheckpoint,
|
|
107
|
+
timestampIso: toIso(health.latestCheckpoint.timestamp)
|
|
108
|
+
} : null,
|
|
109
|
+
checkpointLag: health.checkpointLag,
|
|
110
|
+
checkpointAgeMs: health.checkpointAgeMs,
|
|
111
|
+
checkpointAge: formatDurationCompact(health.checkpointAgeMs),
|
|
112
|
+
unfinalizedCount: health.unfinalizedCount,
|
|
113
|
+
oldestUnfinalizedTimestamp: health.oldestUnfinalizedTimestamp,
|
|
114
|
+
oldestUnfinalizedTimestampIso: toIso(health.oldestUnfinalizedTimestamp),
|
|
115
|
+
oldestUnfinalizedAgeMs,
|
|
116
|
+
oldestUnfinalizedAge: formatDurationCompact(oldestUnfinalizedAgeMs),
|
|
117
|
+
nowIso: new Date(now).toISOString(),
|
|
118
|
+
violations: {
|
|
119
|
+
lag: lagViolation,
|
|
120
|
+
age: ageViolation,
|
|
121
|
+
unfinalized: unfinalizedViolation
|
|
122
|
+
},
|
|
123
|
+
thresholds: {
|
|
124
|
+
checkpointLag: lagThreshold,
|
|
125
|
+
checkpointAgeMs: ageThresholdMs,
|
|
126
|
+
unfinalizedAgeMs: unfinalizedAgeThresholdMs
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Returns `true` unless `DASHBOARD_ENABLED` is explicitly set to `0` or `false`.
|
|
132
|
+
*/
|
|
133
|
+
function isDashboardEnabled(env = process.env) {
|
|
134
|
+
const raw = String(env.DASHBOARD_ENABLED ?? "").trim().toLowerCase();
|
|
135
|
+
if (raw === "0" || raw === "false") return false;
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
function createNodeMaintenanceController(options) {
|
|
139
|
+
const env = options.env ?? process.env;
|
|
140
|
+
const requireAllowEnv = options.requireAllowUpdateTokenDistributionEnv ?? true;
|
|
141
|
+
let isPruning = false;
|
|
142
|
+
let lastPruneAt = null;
|
|
143
|
+
let lastPruneError = null;
|
|
144
|
+
let isUpdatingTokenDistribution = false;
|
|
145
|
+
let lastTokenDistributionAt = null;
|
|
146
|
+
let lastTokenDistributionError = null;
|
|
147
|
+
let isSyncingNow = false;
|
|
148
|
+
let lastSyncNowMs = 0;
|
|
149
|
+
let lastSyncNowAt = null;
|
|
150
|
+
let lastReplayFilterPersistAt = null;
|
|
151
|
+
return {
|
|
152
|
+
getStatusSummary: () => ({
|
|
153
|
+
isPruning,
|
|
154
|
+
lastPruneAt,
|
|
155
|
+
lastPruneError,
|
|
156
|
+
isUpdatingTokenDistribution: isUpdatingTokenDistribution || Boolean(options.resolver.tokenDistribution?.isProcessing),
|
|
157
|
+
lastTokenDistributionAt,
|
|
158
|
+
lastTokenDistributionError,
|
|
159
|
+
isSyncingNow,
|
|
160
|
+
lastSyncNowAt,
|
|
161
|
+
lastReplayFilterPersistAt
|
|
162
|
+
}),
|
|
163
|
+
async triggerSyncNow() {
|
|
164
|
+
const runtime = options.resolver.getNodeRuntime?.();
|
|
165
|
+
if (!runtime || typeof runtime.triggerSyncOrProbe !== "function") return {
|
|
166
|
+
triggered: false,
|
|
167
|
+
mode: "single",
|
|
168
|
+
message: "Standalone validator does not require upstream sync polling"
|
|
169
|
+
};
|
|
170
|
+
if (isSyncingNow) throw new NodePreferencesError("SYNC_IN_PROGRESS", "Sync/probe operation is already in progress", 409);
|
|
171
|
+
const now = Date.now();
|
|
172
|
+
if (lastSyncNowMs > 0 && now - lastSyncNowMs < SYNC_NOW_COOLDOWN_MS) throw new NodePreferencesError("COOLDOWN_ACTIVE", `Manual sync/probe cooldown active; retry in ${Math.max(1, Math.ceil((SYNC_NOW_COOLDOWN_MS - (now - lastSyncNowMs)) / 1e3))}s`, 429);
|
|
173
|
+
isSyncingNow = true;
|
|
174
|
+
lastSyncNowMs = now;
|
|
175
|
+
try {
|
|
176
|
+
const result = await runtime.triggerSyncOrProbe();
|
|
177
|
+
lastSyncNowAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
178
|
+
return {
|
|
179
|
+
...result,
|
|
180
|
+
triggeredAt: lastSyncNowAt
|
|
181
|
+
};
|
|
182
|
+
} finally {
|
|
183
|
+
isSyncingNow = false;
|
|
184
|
+
}
|
|
185
|
+
},
|
|
186
|
+
async triggerReloadPreferences() {
|
|
187
|
+
if (!options.preferencesManager) throw new NodePreferencesError("NOT_CONFIGURED", "Preferences manager is not configured on this node", 404);
|
|
188
|
+
const snapshot = await options.preferencesManager.reload();
|
|
189
|
+
return {
|
|
190
|
+
reloaded: true,
|
|
191
|
+
reloadedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
192
|
+
config: snapshot
|
|
193
|
+
};
|
|
194
|
+
},
|
|
195
|
+
async triggerPersistReplayFilter() {
|
|
196
|
+
const filter = options.replayFilter;
|
|
197
|
+
if (!filter || typeof filter.dump !== "function") return {
|
|
198
|
+
persisted: false,
|
|
199
|
+
persistedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
200
|
+
};
|
|
201
|
+
filter.dump();
|
|
202
|
+
lastReplayFilterPersistAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
203
|
+
return {
|
|
204
|
+
persisted: true,
|
|
205
|
+
persistedAt: lastReplayFilterPersistAt
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
triggerIndexDbPrune(params = {}) {
|
|
209
|
+
if (!options.pruneIndexDbFn) throw new NodePreferencesError("NOT_SUPPORTED", "IndexDB prune is not configured on this node", 404);
|
|
210
|
+
if (isPruning) throw new NodePreferencesError("PRUNE_IN_PROGRESS", "prune is already in progress", 409);
|
|
211
|
+
isPruning = true;
|
|
212
|
+
lastPruneError = null;
|
|
213
|
+
Promise.resolve(options.pruneIndexDbFn({ findOnly: Boolean(params.findOnly) })).then(() => {
|
|
214
|
+
lastPruneAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
215
|
+
}).catch((err) => {
|
|
216
|
+
lastPruneError = err instanceof Error ? err.message : String(err);
|
|
217
|
+
}).finally(() => {
|
|
218
|
+
isPruning = false;
|
|
219
|
+
});
|
|
220
|
+
return {
|
|
221
|
+
started: true,
|
|
222
|
+
message: "processing..."
|
|
223
|
+
};
|
|
224
|
+
},
|
|
225
|
+
async triggerUpdateTokenDistribution(params = {}) {
|
|
226
|
+
if (requireAllowEnv && env.ALLOW_UPDATE_TOKEN_DISTRIBUTION !== "1") throw new NodePreferencesError("FORBIDDEN", "not allowed", 403);
|
|
227
|
+
if (!requireAllowEnv && env.ALLOW_UPDATE_TOKEN_DISTRIBUTION === "0") throw new NodePreferencesError("FORBIDDEN", "not allowed", 403);
|
|
228
|
+
if (typeof options.resolver.updateTokenDistribution !== "function") throw new NodePreferencesError("NOT_SUPPORTED", "Token distribution update is not supported", 404);
|
|
229
|
+
if (isUpdatingTokenDistribution || options.resolver.tokenDistribution?.isProcessing) throw new NodePreferencesError("CONFLICT", "token distribution update is already in progress", 409);
|
|
230
|
+
isUpdatingTokenDistribution = true;
|
|
231
|
+
lastTokenDistributionError = null;
|
|
232
|
+
try {
|
|
233
|
+
const result = await options.resolver.updateTokenDistribution({
|
|
234
|
+
force: Boolean(params.force),
|
|
235
|
+
...params.tokenAddress ? { tokenAddress: params.tokenAddress } : {}
|
|
236
|
+
});
|
|
237
|
+
lastTokenDistributionAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
238
|
+
return result;
|
|
239
|
+
} catch (err) {
|
|
240
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
241
|
+
lastTokenDistributionError = msg;
|
|
242
|
+
const isInvalid = err?.code === "INVALID_PARAMS" || /invalid|does not exist/i.test(msg);
|
|
243
|
+
throw new NodePreferencesError(isInvalid ? "INVALID_PARAMS" : "INTERNAL_ERROR", isInvalid ? msg || "invalid parameters" : "failed to update token distribution", isInvalid ? 400 : 500);
|
|
244
|
+
} finally {
|
|
245
|
+
isUpdatingTokenDistribution = false;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
async function readBoundedObjectBody(req, maxBytes, allowEmpty = false) {
|
|
251
|
+
const declaredLen = req.headers["content-length"];
|
|
252
|
+
if (typeof declaredLen === "string" && declaredLen.trim()) {
|
|
253
|
+
const parsedLen = Number(declaredLen);
|
|
254
|
+
if (Number.isFinite(parsedLen) && parsedLen > maxBytes) return {
|
|
255
|
+
ok: false,
|
|
256
|
+
status: 413,
|
|
257
|
+
code: "PAYLOAD_TOO_LARGE",
|
|
258
|
+
error: `Request body exceeds ${maxBytes}-byte limit`
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
if (req.body !== void 0 && !Buffer.isBuffer(req.body) && typeof req.body !== "string") {
|
|
262
|
+
if (req.body === null || typeof req.body !== "object" || Array.isArray(req.body)) {
|
|
263
|
+
if (allowEmpty && !req.body) return {
|
|
264
|
+
ok: true,
|
|
265
|
+
body: {}
|
|
266
|
+
};
|
|
267
|
+
return {
|
|
268
|
+
ok: false,
|
|
269
|
+
status: 400,
|
|
270
|
+
code: "INVALID_JSON",
|
|
271
|
+
error: "Request body must be a JSON object"
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
if (Buffer.byteLength(JSON.stringify(req.body), "utf8") > maxBytes) return {
|
|
275
|
+
ok: false,
|
|
276
|
+
status: 413,
|
|
277
|
+
code: "PAYLOAD_TOO_LARGE",
|
|
278
|
+
error: `Request body exceeds ${maxBytes}-byte limit`
|
|
279
|
+
};
|
|
280
|
+
return {
|
|
281
|
+
ok: true,
|
|
282
|
+
body: req.body
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
if (typeof req.body === "string" || Buffer.isBuffer(req.body)) {
|
|
286
|
+
const rawBuf = Buffer.isBuffer(req.body) ? req.body : Buffer.from(req.body, "utf8");
|
|
287
|
+
if (rawBuf.byteLength > maxBytes) return {
|
|
288
|
+
ok: false,
|
|
289
|
+
status: 413,
|
|
290
|
+
code: "PAYLOAD_TOO_LARGE",
|
|
291
|
+
error: `Request body exceeds ${maxBytes}-byte limit`
|
|
292
|
+
};
|
|
293
|
+
const rawText = rawBuf.toString("utf8").trim();
|
|
294
|
+
if (!rawText && allowEmpty) return {
|
|
295
|
+
ok: true,
|
|
296
|
+
body: {}
|
|
297
|
+
};
|
|
298
|
+
try {
|
|
299
|
+
const parsed = JSON.parse(rawText);
|
|
300
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {
|
|
301
|
+
ok: false,
|
|
302
|
+
status: 400,
|
|
303
|
+
code: "INVALID_JSON",
|
|
304
|
+
error: "Request body must be a JSON object"
|
|
305
|
+
};
|
|
306
|
+
return {
|
|
307
|
+
ok: true,
|
|
308
|
+
body: parsed
|
|
309
|
+
};
|
|
310
|
+
} catch {
|
|
311
|
+
return {
|
|
312
|
+
ok: false,
|
|
313
|
+
status: 400,
|
|
314
|
+
code: "INVALID_JSON",
|
|
315
|
+
error: "Malformed JSON body"
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return new Promise((resolve) => {
|
|
320
|
+
const chunks = [];
|
|
321
|
+
let total = 0;
|
|
322
|
+
let settled = false;
|
|
323
|
+
const finish = (result) => {
|
|
324
|
+
if (settled) return;
|
|
325
|
+
settled = true;
|
|
326
|
+
resolve(result);
|
|
327
|
+
};
|
|
328
|
+
req.on("data", (chunk) => {
|
|
329
|
+
if (settled) return;
|
|
330
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
|
|
331
|
+
total += buf.byteLength;
|
|
332
|
+
if (total > maxBytes) {
|
|
333
|
+
req.pause();
|
|
334
|
+
finish({
|
|
335
|
+
ok: false,
|
|
336
|
+
status: 413,
|
|
337
|
+
code: "PAYLOAD_TOO_LARGE",
|
|
338
|
+
error: `Request body exceeds ${maxBytes}-byte limit`
|
|
339
|
+
});
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
chunks.push(buf);
|
|
343
|
+
});
|
|
344
|
+
req.on("end", () => {
|
|
345
|
+
if (settled) return;
|
|
346
|
+
const text = Buffer.concat(chunks, total).toString("utf8").trim();
|
|
347
|
+
if (!text && allowEmpty) {
|
|
348
|
+
finish({
|
|
349
|
+
ok: true,
|
|
350
|
+
body: {}
|
|
351
|
+
});
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
try {
|
|
355
|
+
const parsed = JSON.parse(text);
|
|
356
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
357
|
+
finish({
|
|
358
|
+
ok: false,
|
|
359
|
+
status: 400,
|
|
360
|
+
code: "INVALID_JSON",
|
|
361
|
+
error: "Request body must be a JSON object"
|
|
362
|
+
});
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
finish({
|
|
366
|
+
ok: true,
|
|
367
|
+
body: parsed
|
|
368
|
+
});
|
|
369
|
+
} catch {
|
|
370
|
+
finish({
|
|
371
|
+
ok: false,
|
|
372
|
+
status: 400,
|
|
373
|
+
code: "INVALID_JSON",
|
|
374
|
+
error: "Malformed JSON body"
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
req.on("error", () => {
|
|
379
|
+
finish({
|
|
380
|
+
ok: false,
|
|
381
|
+
status: 400,
|
|
382
|
+
code: "STREAM_ERROR",
|
|
383
|
+
error: "Failed to read request body"
|
|
384
|
+
});
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
async function statSafeSize(filePath) {
|
|
389
|
+
try {
|
|
390
|
+
const st = await fs.promises.stat(filePath);
|
|
391
|
+
return {
|
|
392
|
+
exists: st.isFile(),
|
|
393
|
+
size: st.isFile() ? st.size : 0
|
|
394
|
+
};
|
|
395
|
+
} catch {
|
|
396
|
+
return {
|
|
397
|
+
exists: false,
|
|
398
|
+
size: 0
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
async function statSqliteTriplet(key, label, targetPath) {
|
|
403
|
+
if (!targetPath) return {
|
|
404
|
+
key,
|
|
405
|
+
label,
|
|
406
|
+
fileName: `${key}.sqlite`,
|
|
407
|
+
exists: false,
|
|
408
|
+
mainBytes: 0,
|
|
409
|
+
walBytes: 0,
|
|
410
|
+
shmBytes: 0,
|
|
411
|
+
totalBytes: 0,
|
|
412
|
+
walWarning: false
|
|
413
|
+
};
|
|
414
|
+
const [main, wal, shm] = await Promise.all([
|
|
415
|
+
statSafeSize(targetPath),
|
|
416
|
+
statSafeSize(`${targetPath}-wal`),
|
|
417
|
+
statSafeSize(`${targetPath}-shm`)
|
|
418
|
+
]);
|
|
419
|
+
const totalBytes = main.size + wal.size + shm.size;
|
|
420
|
+
const walWarning = wal.size > 64 * 1024 * 1024 && wal.size > main.size;
|
|
421
|
+
return {
|
|
422
|
+
key,
|
|
423
|
+
label,
|
|
424
|
+
fileName: path.basename(targetPath),
|
|
425
|
+
filePath: targetPath,
|
|
426
|
+
exists: main.exists,
|
|
427
|
+
mainBytes: main.size,
|
|
428
|
+
walBytes: wal.size,
|
|
429
|
+
shmBytes: shm.size,
|
|
430
|
+
totalBytes,
|
|
431
|
+
walWarning
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
function createNodeDashboardRouter(options) {
|
|
435
|
+
const env = options.env ?? process.env;
|
|
436
|
+
const authGuard = options.authGuard ?? createAdminAuthGuard({ env });
|
|
437
|
+
const maintenance = options.maintenanceController ?? createNodeMaintenanceController({
|
|
438
|
+
resolver: options.resolver,
|
|
439
|
+
preferencesManager: options.preferencesManager,
|
|
440
|
+
env
|
|
441
|
+
});
|
|
442
|
+
const fastTtlMs = options.fastCacheTtlMs ?? FAST_DASHBOARD_TTL_MS;
|
|
443
|
+
const slowTtlMs = options.slowCacheTtlMs ?? SLOW_STORAGE_TTL_MS;
|
|
444
|
+
let slowCache = null;
|
|
445
|
+
let slowInFlight = null;
|
|
446
|
+
const fastCache = /* @__PURE__ */ new Map();
|
|
447
|
+
const fastInFlight = /* @__PURE__ */ new Map();
|
|
448
|
+
const invalidateFastCache = () => {
|
|
449
|
+
fastCache.clear();
|
|
450
|
+
};
|
|
451
|
+
const resolveDbPaths = () => {
|
|
452
|
+
const baseDir = options.dataDir ? path.resolve(options.dataDir) : null;
|
|
453
|
+
const trustedEnv = String(env.TRUSTED_SQLITE_PATH || "").trim();
|
|
454
|
+
return {
|
|
455
|
+
statedb: options.dbPaths?.statedb || (env.STATEDB_SQLITE_PATH ? path.resolve(env.STATEDB_SQLITE_PATH) : baseDir ? path.join(baseDir, "statedb.sqlite") : null),
|
|
456
|
+
indexdb: options.dbPaths?.indexdb || (baseDir ? path.join(baseDir, "indexdb.sqlite") : null),
|
|
457
|
+
ledger: options.dbPaths?.ledger || (env.LEDGER_SQLITE_PATH ? path.resolve(env.LEDGER_SQLITE_PATH) : baseDir ? path.join(baseDir, "ledger.sqlite") : null),
|
|
458
|
+
trusted: options.dbPaths?.trusted || (trustedEnv && trustedEnv !== "1" ? path.resolve(trustedEnv) : baseDir ? path.join(baseDir, "trusted.sqlite") : null)
|
|
459
|
+
};
|
|
460
|
+
};
|
|
461
|
+
const getSlowStorageTelemetry = async () => {
|
|
462
|
+
const now = Date.now();
|
|
463
|
+
if (slowCache && slowCache.expiresAt > now) return slowCache.data;
|
|
464
|
+
if (slowInFlight) return slowInFlight;
|
|
465
|
+
slowInFlight = (async () => {
|
|
466
|
+
const dbPaths = resolveDbPaths();
|
|
467
|
+
const idx = options.resolver.indexdb;
|
|
468
|
+
const safeCount = async (table) => {
|
|
469
|
+
if (!table || typeof table.count !== "function") return 0;
|
|
470
|
+
try {
|
|
471
|
+
const val = await table.count();
|
|
472
|
+
return Number.isFinite(Number(val)) ? Number(val) : 0;
|
|
473
|
+
} catch {
|
|
474
|
+
return 0;
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
const [statedbFiles, indexdbFiles, ledgerFiles, trustedFiles, txCount, accountCount, assetCount, factoryCount, tokenCount, stakeCount, delegationCount, rollupCount] = await Promise.all([
|
|
478
|
+
statSqliteTriplet("statedb", "StateDB", dbPaths.statedb),
|
|
479
|
+
statSqliteTriplet("indexdb", "IndexDB", dbPaths.indexdb),
|
|
480
|
+
statSqliteTriplet("ledger", "Verifiable Ledger", dbPaths.ledger),
|
|
481
|
+
statSqliteTriplet("trusted", "Trusted Anchor DB", dbPaths.trusted),
|
|
482
|
+
safeCount(idx?.tx),
|
|
483
|
+
safeCount(idx?.account),
|
|
484
|
+
safeCount(idx?.asset),
|
|
485
|
+
safeCount(idx?.factory),
|
|
486
|
+
safeCount(idx?.token),
|
|
487
|
+
safeCount(idx?.stake),
|
|
488
|
+
safeCount(idx?.delegation),
|
|
489
|
+
safeCount(idx?.rollup)
|
|
490
|
+
]);
|
|
491
|
+
const databases = [
|
|
492
|
+
statedbFiles,
|
|
493
|
+
indexdbFiles,
|
|
494
|
+
ledgerFiles,
|
|
495
|
+
trustedFiles
|
|
496
|
+
];
|
|
497
|
+
const totalSqliteBytes = databases.reduce((sum, item) => sum + item.totalBytes, 0);
|
|
498
|
+
const totalWalBytes = databases.reduce((sum, item) => sum + item.walBytes, 0);
|
|
499
|
+
const data = {
|
|
500
|
+
collectedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
501
|
+
databases,
|
|
502
|
+
totalSqliteBytes,
|
|
503
|
+
totalWalBytes,
|
|
504
|
+
entityCounts: {
|
|
505
|
+
tx: txCount,
|
|
506
|
+
account: accountCount,
|
|
507
|
+
asset: assetCount,
|
|
508
|
+
factory: factoryCount,
|
|
509
|
+
token: tokenCount,
|
|
510
|
+
stake: stakeCount,
|
|
511
|
+
delegation: delegationCount,
|
|
512
|
+
rollup: rollupCount
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
slowCache = {
|
|
516
|
+
expiresAt: Date.now() + slowTtlMs,
|
|
517
|
+
data
|
|
518
|
+
};
|
|
519
|
+
return data;
|
|
520
|
+
})().finally(() => {
|
|
521
|
+
slowInFlight = null;
|
|
522
|
+
});
|
|
523
|
+
return slowInFlight;
|
|
524
|
+
};
|
|
525
|
+
const resolveEffectiveRoleAndMode = () => {
|
|
526
|
+
const runtime = options.resolver.getNodeRuntime?.();
|
|
527
|
+
if (runtime) return {
|
|
528
|
+
role: runtime.role,
|
|
529
|
+
consensusMode: runtime.getConsensusMode?.() === "hotstuff" ? "hotstuff" : "single"
|
|
530
|
+
};
|
|
531
|
+
const rawRole = String(env.CHAIN_ROLE || "").trim().toLowerCase();
|
|
532
|
+
const rawMode = String(env.CHAIN_MODE || "").trim().toLowerCase();
|
|
533
|
+
return {
|
|
534
|
+
role: rawRole === "follower" || rawRole === "standby" ? rawRole : rawMode === "readonly" ? "follower" : "validator",
|
|
535
|
+
consensusMode: String(env.CONSENSUS_MODE || "").trim().toLowerCase() === "hotstuff" ? "hotstuff" : "single"
|
|
536
|
+
};
|
|
537
|
+
};
|
|
538
|
+
const buildDashboardPayload = async (isAdmin) => {
|
|
539
|
+
const cacheKey = isAdmin ? "admin" : "public";
|
|
540
|
+
const now = Date.now();
|
|
541
|
+
const hit = fastCache.get(cacheKey);
|
|
542
|
+
if (hit && hit.expiresAt > now) return hit.payload;
|
|
543
|
+
const pending = fastInFlight.get(cacheKey);
|
|
544
|
+
if (pending) return pending;
|
|
545
|
+
const promise = (async () => {
|
|
546
|
+
const runtime = options.resolver.getNodeRuntime?.();
|
|
547
|
+
const extLedger = options.resolver.ledger;
|
|
548
|
+
const { role, consensusMode } = resolveEffectiveRoleAndMode();
|
|
549
|
+
const effectiveThresholds = options.preferencesManager?.getEffectiveHealthThresholds();
|
|
550
|
+
const [ledgerHealth, followerStatusRaw, runtimeDiagnostics, localStateCommitHash, slowStorage] = await Promise.all([
|
|
551
|
+
collectLedgerHealthSummary({
|
|
552
|
+
ledger: options.resolver.ledger,
|
|
553
|
+
runtime,
|
|
554
|
+
retentionMode: options.retentionMode,
|
|
555
|
+
thresholds: effectiveThresholds,
|
|
556
|
+
env
|
|
557
|
+
}),
|
|
558
|
+
typeof options.resolver.getFollowerStatus === "function" ? options.resolver.getFollowerStatus().catch(() => null) : Promise.resolve(null),
|
|
559
|
+
typeof runtime?.getRuntimeDiagnostics === "function" ? Promise.resolve(runtime.getRuntimeDiagnostics({ includePrivateTopology: isAdmin })).catch(() => null) : Promise.resolve(null),
|
|
560
|
+
typeof options.resolver.statedb?.getCurrentCommitHash === "function" ? options.resolver.statedb.getCurrentCommitHash().catch(() => "UNKNOWN") : Promise.resolve("UNKNOWN"),
|
|
561
|
+
getSlowStorageTelemetry()
|
|
562
|
+
]);
|
|
563
|
+
const anchorPublisher = extLedger.getAnchorPublisher?.();
|
|
564
|
+
const latestCpHeight = ledgerHealth.latestCheckpoint?.height;
|
|
565
|
+
const latestAnchorReceipt = typeof anchorPublisher?.getLatestReceipt === "function" ? anchorPublisher.getLatestReceipt() : latestCpHeight && typeof anchorPublisher?.getReceiptAsync === "function" ? await anchorPublisher.getReceiptAsync(latestCpHeight).catch(() => null) : latestCpHeight && typeof anchorPublisher?.getReceipt === "function" ? anchorPublisher.getReceipt(latestCpHeight) : null;
|
|
566
|
+
const halted = Boolean(runtime?.isHalted?.() || followerStatusRaw?.halted);
|
|
567
|
+
const haltReason = runtime?.getHaltReason?.() ?? followerStatusRaw?.haltReason ?? null;
|
|
568
|
+
const synced = followerStatusRaw ? followerStatusRaw.synced : runtime ? await Promise.resolve(runtime.isSynced()) : true;
|
|
569
|
+
const writePolicy = runtime?.writePolicy || followerStatusRaw?.writePolicy || (String(env.CHAIN_WRITE_POLICY || "").trim().toLowerCase() === "forward" ? "forward" : "reject");
|
|
570
|
+
const writable = halted ? false : typeof runtime?.shouldHandleWriteLocally === "function" ? runtime.shouldHandleWriteLocally() : !runtime ? !options.resolver.readonly && role === "validator" : runtime.role === "validator" && !options.resolver.readonly;
|
|
571
|
+
const chainId = options.resolver.config?.chainId || options.resolver.ledger.chainId;
|
|
572
|
+
const version = options.resolver.config?.version || "unknown";
|
|
573
|
+
const mem = process.memoryUsage();
|
|
574
|
+
const rawPipeline = typeof options.resolver.getPipelineTelemetry === "function" ? options.resolver.getPipelineTelemetry() : null;
|
|
575
|
+
const acceptedTotal = rawPipeline?.txAcceptedTotal ?? rawPipeline?.acceptedTotal ?? 0;
|
|
576
|
+
const forwardedTotal = rawPipeline?.txForwardedTotal ?? rawPipeline?.forwardedTotal ?? 0;
|
|
577
|
+
const persistedFailedTotal = rawPipeline?.txPersistedFailedTotal ?? rawPipeline?.persistedFailedTotal ?? 0;
|
|
578
|
+
const preFlightRejectedTotal = rawPipeline?.txPreFlightRejectedTotal ?? rawPipeline?.preFlightRejectedTotal ?? 0;
|
|
579
|
+
const pipeline = {
|
|
580
|
+
queueDepth: rawPipeline?.queueDepth ?? 0,
|
|
581
|
+
queuePending: rawPipeline?.queuePending ?? 0,
|
|
582
|
+
queueWaiting: rawPipeline?.queueWaiting ?? rawPipeline?.queueDepth ?? 0,
|
|
583
|
+
inFlightPreFlights: rawPipeline?.inFlightPreFlights ?? 0,
|
|
584
|
+
maxTxRequest: rawPipeline?.maxTxRequest ?? options.resolver.getMaxTxRequest?.() ?? 200,
|
|
585
|
+
concurrency: rawPipeline?.concurrency ?? 10,
|
|
586
|
+
rollingWindowSeconds: rawPipeline?.rollingWindowSeconds ?? 60,
|
|
587
|
+
committedInWindow: rawPipeline?.committedInWindow ?? Math.round((rawPipeline?.tps60s ?? 0) * 60),
|
|
588
|
+
tps10s: rawPipeline?.tps10s ?? 0,
|
|
589
|
+
tps60s: rawPipeline?.tps60s ?? 0,
|
|
590
|
+
acceptedTotal,
|
|
591
|
+
forwardedTotal,
|
|
592
|
+
persistedFailedTotal,
|
|
593
|
+
preFlightRejectedTotal,
|
|
594
|
+
txAcceptedTotal: acceptedTotal,
|
|
595
|
+
txForwardedTotal: forwardedTotal,
|
|
596
|
+
txPersistedFailedTotal: persistedFailedTotal,
|
|
597
|
+
txPreFlightRejectedTotal: preFlightRejectedTotal
|
|
598
|
+
};
|
|
599
|
+
const gasSecurity = getGasSecuritySummary(options.resolver.statedb, options.resolver.config);
|
|
600
|
+
const prefSnap = options.preferencesManager?.getSnapshot();
|
|
601
|
+
const sanitizedDatabases = slowStorage.databases.map((db) => ({
|
|
602
|
+
key: db.key,
|
|
603
|
+
label: db.label,
|
|
604
|
+
fileName: db.fileName,
|
|
605
|
+
...isAdmin && db.filePath ? { filePath: db.filePath } : {},
|
|
606
|
+
exists: db.exists,
|
|
607
|
+
mainBytes: db.mainBytes,
|
|
608
|
+
walBytes: db.walBytes,
|
|
609
|
+
shmBytes: db.shmBytes,
|
|
610
|
+
totalBytes: db.totalBytes,
|
|
611
|
+
walWarning: db.walWarning
|
|
612
|
+
}));
|
|
613
|
+
const overallStatus = halted ? "halted" : !synced || !ledgerHealth.healthy || ledgerHealth.witnessCircuitBroken ? "degraded" : "healthy";
|
|
614
|
+
const payload = {
|
|
615
|
+
nowIso: (/* @__PURE__ */ new Date()).toISOString(),
|
|
616
|
+
overallStatus,
|
|
617
|
+
auth: {
|
|
618
|
+
configured: authGuard.isConfigured(),
|
|
619
|
+
authenticated: isAdmin,
|
|
620
|
+
dashboardRequireAuth: String(env.DASHBOARD_REQUIRE_AUTH || "").trim().toLowerCase() === "1" || String(env.DASHBOARD_REQUIRE_AUTH || "").trim().toLowerCase() === "true"
|
|
621
|
+
},
|
|
622
|
+
node: {
|
|
623
|
+
chainId,
|
|
624
|
+
version,
|
|
625
|
+
nodeRole: role,
|
|
626
|
+
consensusMode,
|
|
627
|
+
writePolicy,
|
|
628
|
+
writable,
|
|
629
|
+
synced,
|
|
630
|
+
halted,
|
|
631
|
+
haltReason,
|
|
632
|
+
uptimeSeconds: Math.floor(process.uptime()),
|
|
633
|
+
localSequence: followerStatusRaw?.localSequence ?? ledgerHealth.latestSequence,
|
|
634
|
+
upstreamSequence: followerStatusRaw?.upstreamSequence ?? ledgerHealth.latestSequence,
|
|
635
|
+
syncLagEntries: followerStatusRaw?.syncLagEntries ?? 0,
|
|
636
|
+
localStateCommitHash: followerStatusRaw?.localStateCommitHash || localStateCommitHash,
|
|
637
|
+
verifiedCheckpointHeight: followerStatusRaw?.verifiedCheckpointHeight ?? ledgerHealth.latestCheckpoint?.height ?? 0,
|
|
638
|
+
verifiedCheckpointHash: followerStatusRaw?.verifiedCheckpointHash ?? (typeof ledgerHealth.latestCheckpoint?.hash === "string" ? ledgerHealth.latestCheckpoint.hash : null),
|
|
639
|
+
lastUpstreamSuccessAt: followerStatusRaw?.lastUpstreamSuccessAt ?? null,
|
|
640
|
+
...isAdmin && followerStatusRaw?.activeLeaderUrl ? { activeLeaderUrl: followerStatusRaw.activeLeaderUrl } : {}
|
|
641
|
+
},
|
|
642
|
+
ledgerHealth,
|
|
643
|
+
consensus: {
|
|
644
|
+
mode: consensusMode,
|
|
645
|
+
view: runtime?.getConsensusView?.() ?? null,
|
|
646
|
+
highQC: runtime?.getHighQC?.() ?? null,
|
|
647
|
+
lockedQC: runtime?.getLockedQC?.() ?? null,
|
|
648
|
+
lastTC: runtime?.getLastTC?.() ?? null,
|
|
649
|
+
runtime: runtimeDiagnostics
|
|
650
|
+
},
|
|
651
|
+
da: {
|
|
652
|
+
retentionMode: ledgerHealth.retentionMode,
|
|
653
|
+
snapshotBaseUrl: resolveSafeSnapshotBaseUrl(env),
|
|
654
|
+
witnessQuorum: ledgerHealth.witnessQuorum,
|
|
655
|
+
witnessCircuitBroken: ledgerHealth.witnessCircuitBroken,
|
|
656
|
+
witnessFraudAlertCount: ledgerHealth.witnessFraudAlertCount,
|
|
657
|
+
latestAnchorReceipt
|
|
658
|
+
},
|
|
659
|
+
pipeline,
|
|
660
|
+
gasSecurity,
|
|
661
|
+
storage: {
|
|
662
|
+
collectedAt: slowStorage.collectedAt,
|
|
663
|
+
totalSqliteBytes: slowStorage.totalSqliteBytes,
|
|
664
|
+
totalWalBytes: slowStorage.totalWalBytes,
|
|
665
|
+
databases: sanitizedDatabases,
|
|
666
|
+
entityCounts: slowStorage.entityCounts
|
|
667
|
+
},
|
|
668
|
+
resources: isAdmin ? {
|
|
669
|
+
pid: process.pid,
|
|
670
|
+
nodeVersion: process.version,
|
|
671
|
+
platform: process.platform,
|
|
672
|
+
arch: process.arch,
|
|
673
|
+
cpuCount: os.cpus()?.length ?? 1,
|
|
674
|
+
loadAvg1m: Number((os.loadavg?.()[0] ?? 0).toFixed(2)),
|
|
675
|
+
rssBytes: mem.rss,
|
|
676
|
+
heapUsedBytes: mem.heapUsed,
|
|
677
|
+
heapTotalBytes: mem.heapTotal,
|
|
678
|
+
externalBytes: mem.external
|
|
679
|
+
} : {
|
|
680
|
+
rssBytes: mem.rss,
|
|
681
|
+
heapUsedBytes: mem.heapUsed
|
|
682
|
+
},
|
|
683
|
+
preferencesSummary: {
|
|
684
|
+
configured: Boolean(options.preferencesManager),
|
|
685
|
+
updatedAt: prefSnap?.updatedAt ?? null,
|
|
686
|
+
blockedAccountCount: prefSnap?.blockedAccounts.length ?? 0,
|
|
687
|
+
trustedAccountCount: prefSnap?.trustedAccounts.length ?? 0,
|
|
688
|
+
reservedSymbolCount: prefSnap?.reservedSymbols.length ?? 0
|
|
689
|
+
},
|
|
690
|
+
maintenance: maintenance.getStatusSummary()
|
|
691
|
+
};
|
|
692
|
+
fastCache.set(cacheKey, {
|
|
693
|
+
expiresAt: Date.now() + fastTtlMs,
|
|
694
|
+
payload
|
|
695
|
+
});
|
|
696
|
+
return payload;
|
|
697
|
+
})().finally(() => {
|
|
698
|
+
fastInFlight.delete(cacheKey);
|
|
699
|
+
});
|
|
700
|
+
fastInFlight.set(cacheKey, promise);
|
|
701
|
+
return promise;
|
|
702
|
+
};
|
|
703
|
+
const runAdminRoute = (req, res, next, handler) => {
|
|
704
|
+
authGuard.requireAdmin(req, res, (err) => {
|
|
705
|
+
if (err) {
|
|
706
|
+
next(err);
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
Promise.resolve(handler(req, res)).catch(next);
|
|
710
|
+
});
|
|
711
|
+
};
|
|
712
|
+
return (req, res, next) => {
|
|
713
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
714
|
+
res.setHeader("X-Frame-Options", "DENY");
|
|
715
|
+
res.setHeader("Cache-Control", "no-store");
|
|
716
|
+
if (!isDashboardEnabled(env)) {
|
|
717
|
+
res.status(404).json({
|
|
718
|
+
code: "DASHBOARD_DISABLED",
|
|
719
|
+
error: "Node dashboard is disabled"
|
|
720
|
+
});
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
const method = String(req.method || "GET").toUpperCase();
|
|
724
|
+
const isGetOrHead = method === "GET" || method === "HEAD";
|
|
725
|
+
const rawPath = String(req.path || (req.url || "/").split("?")[0] || "/");
|
|
726
|
+
const routePath = rawPath.length > 1 ? rawPath.replace(/\/+$/, "") : rawPath;
|
|
727
|
+
if (isGetOrHead && routePath === "/dashboard") {
|
|
728
|
+
if (String(env.DASHBOARD_REQUIRE_AUTH || "").trim().toLowerCase() === "1" || String(env.DASHBOARD_REQUIRE_AUTH || "").trim().toLowerCase() === "true") {
|
|
729
|
+
authGuard.requireAdmin(req, res, () => {
|
|
730
|
+
(async () => {
|
|
731
|
+
try {
|
|
732
|
+
const payload = await buildDashboardPayload(true);
|
|
733
|
+
res.status(200).json(payload);
|
|
734
|
+
} catch (err) {
|
|
735
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
736
|
+
res.status(500).json({
|
|
737
|
+
code: "INTERNAL_ERROR",
|
|
738
|
+
error: message
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
})();
|
|
742
|
+
});
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
const optionalState = authGuard.checkOptionalAdmin ? authGuard.checkOptionalAdmin(req, res) : authGuard.isAuthenticatedRequest(req) ? "admin" : "anonymous";
|
|
746
|
+
if (optionalState === "rate_limited") return;
|
|
747
|
+
(async () => {
|
|
748
|
+
try {
|
|
749
|
+
const payload = await buildDashboardPayload(optionalState === "admin");
|
|
750
|
+
res.status(200).json(payload);
|
|
751
|
+
} catch (err) {
|
|
752
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
753
|
+
res.status(500).json({
|
|
754
|
+
code: "INTERNAL_ERROR",
|
|
755
|
+
error: message
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
})();
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
if (isGetOrHead && routePath === "/config") {
|
|
762
|
+
runAdminRoute(req, res, next, async (_req, resInner) => {
|
|
763
|
+
if (!options.preferencesManager) {
|
|
764
|
+
resInner.status(404).json({
|
|
765
|
+
code: "NOT_CONFIGURED",
|
|
766
|
+
error: "Preferences manager is not configured on this node"
|
|
767
|
+
});
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
const { role, consensusMode } = resolveEffectiveRoleAndMode();
|
|
771
|
+
const runtime = options.resolver.getNodeRuntime?.();
|
|
772
|
+
const runtimeDiag = typeof runtime?.getRuntimeDiagnostics === "function" ? await Promise.resolve(runtime.getRuntimeDiagnostics({ includePrivateTopology: true })).catch(() => null) : null;
|
|
773
|
+
const snap = options.preferencesManager.getSnapshot();
|
|
774
|
+
resInner.status(200).json({
|
|
775
|
+
config: snap,
|
|
776
|
+
effectiveRuntime: {
|
|
777
|
+
role,
|
|
778
|
+
consensusMode,
|
|
779
|
+
writePolicy: runtime?.writePolicy ?? snap.runtime.writePolicy ?? "reject",
|
|
780
|
+
txMaxRequest: options.resolver.getMaxTxRequest?.() ?? snap.runtime.txMaxRequest ?? 200,
|
|
781
|
+
pollIntervalMs: runtimeDiag?.pollIntervalMs ?? snap.runtime.pollIntervalMs ?? null,
|
|
782
|
+
maxSyncLag: runtimeDiag?.maxSyncLag ?? snap.runtime.maxSyncLag ?? null,
|
|
783
|
+
peerUrls: runtimeDiag?.peerUrls ?? snap.runtime.peerUrls ?? [],
|
|
784
|
+
healthThresholds: options.preferencesManager.getEffectiveHealthThresholds()
|
|
785
|
+
},
|
|
786
|
+
capabilities: {
|
|
787
|
+
role,
|
|
788
|
+
consensusMode,
|
|
789
|
+
canEditReservedSymbols: role === "validator" && consensusMode !== "hotstuff",
|
|
790
|
+
canEditFollowerPeers: role !== "validator",
|
|
791
|
+
canEditFollowerSyncParams: role !== "validator"
|
|
792
|
+
}
|
|
793
|
+
});
|
|
794
|
+
});
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
if (method === "PUT" && routePath === "/config") {
|
|
798
|
+
runAdminRoute(req, res, next, async (reqInner, resInner) => {
|
|
799
|
+
if (!options.preferencesManager) {
|
|
800
|
+
resInner.status(404).json({
|
|
801
|
+
code: "NOT_CONFIGURED",
|
|
802
|
+
error: "Preferences manager is not configured on this node"
|
|
803
|
+
});
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
const parsed = await readBoundedObjectBody(reqInner, MAX_CONFIG_BODY_BYTES, false);
|
|
807
|
+
if (!parsed.ok) {
|
|
808
|
+
resInner.status(parsed.status).json({
|
|
809
|
+
code: parsed.code,
|
|
810
|
+
error: parsed.error
|
|
811
|
+
});
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
try {
|
|
815
|
+
const result = await options.preferencesManager.update(parsed.body);
|
|
816
|
+
invalidateFastCache();
|
|
817
|
+
resInner.status(200).json({
|
|
818
|
+
ok: true,
|
|
819
|
+
config: result.snapshot,
|
|
820
|
+
requiresRestart: result.requiresRestart,
|
|
821
|
+
changedRuntimeKeys: result.changedRuntimeKeys
|
|
822
|
+
});
|
|
823
|
+
} catch (err) {
|
|
824
|
+
if (err instanceof NodePreferencesError) {
|
|
825
|
+
resInner.status(err.status).json({
|
|
826
|
+
code: err.code,
|
|
827
|
+
error: err.message
|
|
828
|
+
});
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
const code = err?.code || "INTERNAL_ERROR";
|
|
832
|
+
const status = code === "IMMUTABLE_CLUSTER_CONFIG" ? 403 : code === "INVALID_PARAMS" ? 400 : 500;
|
|
833
|
+
resInner.status(status).json({
|
|
834
|
+
code,
|
|
835
|
+
error: err instanceof Error ? err.message : String(err)
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
});
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
if (method === "POST" && routePath === "/actions/sync-now") {
|
|
842
|
+
runAdminRoute(req, res, next, async (_req, resInner) => {
|
|
843
|
+
try {
|
|
844
|
+
const result = await maintenance.triggerSyncNow();
|
|
845
|
+
invalidateFastCache();
|
|
846
|
+
resInner.status(200).json({
|
|
847
|
+
ok: true,
|
|
848
|
+
...result
|
|
849
|
+
});
|
|
850
|
+
} catch (err) {
|
|
851
|
+
if (err instanceof NodePreferencesError) {
|
|
852
|
+
resInner.status(err.status).json({
|
|
853
|
+
code: err.code,
|
|
854
|
+
error: err.message
|
|
855
|
+
});
|
|
856
|
+
return;
|
|
857
|
+
}
|
|
858
|
+
resInner.status(500).json({
|
|
859
|
+
code: "INTERNAL_ERROR",
|
|
860
|
+
error: err instanceof Error ? err.message : String(err)
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
});
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
if (method === "POST" && routePath === "/actions/reload-preferences") {
|
|
867
|
+
runAdminRoute(req, res, next, async (_req, resInner) => {
|
|
868
|
+
try {
|
|
869
|
+
const result = await maintenance.triggerReloadPreferences();
|
|
870
|
+
invalidateFastCache();
|
|
871
|
+
resInner.status(200).json({
|
|
872
|
+
ok: true,
|
|
873
|
+
...result
|
|
874
|
+
});
|
|
875
|
+
} catch (err) {
|
|
876
|
+
if (err instanceof NodePreferencesError) {
|
|
877
|
+
resInner.status(err.status).json({
|
|
878
|
+
code: err.code,
|
|
879
|
+
error: err.message
|
|
880
|
+
});
|
|
881
|
+
return;
|
|
882
|
+
}
|
|
883
|
+
resInner.status(500).json({
|
|
884
|
+
code: "INTERNAL_ERROR",
|
|
885
|
+
error: err instanceof Error ? err.message : String(err)
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
});
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
if (method === "POST" && routePath === "/actions/persist-replay-filter") {
|
|
892
|
+
runAdminRoute(req, res, next, async (_req, resInner) => {
|
|
893
|
+
try {
|
|
894
|
+
const result = await maintenance.triggerPersistReplayFilter();
|
|
895
|
+
resInner.status(200).json({
|
|
896
|
+
ok: true,
|
|
897
|
+
...result
|
|
898
|
+
});
|
|
899
|
+
} catch (err) {
|
|
900
|
+
resInner.status(500).json({
|
|
901
|
+
code: "INTERNAL_ERROR",
|
|
902
|
+
error: err instanceof Error ? err.message : String(err)
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
});
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
if (method === "POST" && routePath === "/actions/indexdb-prune") {
|
|
909
|
+
runAdminRoute(req, res, next, async (reqInner, resInner) => {
|
|
910
|
+
const parsed = await readBoundedObjectBody(reqInner, MAX_ACTION_BODY_BYTES, true);
|
|
911
|
+
if (!parsed.ok) {
|
|
912
|
+
resInner.status(parsed.status).json({
|
|
913
|
+
code: parsed.code,
|
|
914
|
+
error: parsed.error
|
|
915
|
+
});
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
try {
|
|
919
|
+
const result = maintenance.triggerIndexDbPrune({ findOnly: Boolean(parsed.body.findOnly) });
|
|
920
|
+
invalidateFastCache();
|
|
921
|
+
resInner.status(200).json({
|
|
922
|
+
ok: true,
|
|
923
|
+
...result
|
|
924
|
+
});
|
|
925
|
+
} catch (err) {
|
|
926
|
+
if (err instanceof NodePreferencesError) {
|
|
927
|
+
resInner.status(err.status).json({
|
|
928
|
+
code: err.code,
|
|
929
|
+
error: err.message
|
|
930
|
+
});
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
resInner.status(500).json({
|
|
934
|
+
code: "INTERNAL_ERROR",
|
|
935
|
+
error: err instanceof Error ? err.message : String(err)
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
});
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
if (method === "POST" && routePath === "/actions/update-token-distribution") {
|
|
942
|
+
runAdminRoute(req, res, next, async (reqInner, resInner) => {
|
|
943
|
+
const parsed = await readBoundedObjectBody(reqInner, MAX_ACTION_BODY_BYTES, true);
|
|
944
|
+
if (!parsed.ok) {
|
|
945
|
+
resInner.status(parsed.status).json({
|
|
946
|
+
code: parsed.code,
|
|
947
|
+
error: parsed.error
|
|
948
|
+
});
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
try {
|
|
952
|
+
const tokenAddress = typeof parsed.body.tokenAddress === "string" ? parsed.body.tokenAddress.trim() : void 0;
|
|
953
|
+
const result = await maintenance.triggerUpdateTokenDistribution({
|
|
954
|
+
force: parsed.body.force === true || parsed.body.force === "true",
|
|
955
|
+
tokenAddress
|
|
956
|
+
});
|
|
957
|
+
invalidateFastCache();
|
|
958
|
+
resInner.status(200).json({
|
|
959
|
+
ok: true,
|
|
960
|
+
result
|
|
961
|
+
});
|
|
962
|
+
} catch (err) {
|
|
963
|
+
if (err instanceof NodePreferencesError) {
|
|
964
|
+
resInner.status(err.status).json({
|
|
965
|
+
code: err.code,
|
|
966
|
+
error: err.message
|
|
967
|
+
});
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
resInner.status(500).json({
|
|
971
|
+
code: "INTERNAL_ERROR",
|
|
972
|
+
error: err instanceof Error ? err.message : String(err)
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
});
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
if (isGetOrHead && routePath === "/diagnostics") {
|
|
979
|
+
runAdminRoute(req, res, next, async (_req, resInner) => {
|
|
980
|
+
try {
|
|
981
|
+
const dashboard = await buildDashboardPayload(true);
|
|
982
|
+
const fraudAlerts = (options.resolver.ledger.getWitnessRegistry?.()?.getFraudAlerts() ?? []).slice(-50);
|
|
983
|
+
const chainId = String(options.resolver.config?.chainId || options.resolver.ledger.chainId || "chain").replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
984
|
+
const bundle = {
|
|
985
|
+
exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
986
|
+
schemaVersion: 1,
|
|
987
|
+
dashboard,
|
|
988
|
+
config: options.preferencesManager?.getSnapshot() ?? null,
|
|
989
|
+
witnessFraudAlerts: fraudAlerts
|
|
990
|
+
};
|
|
991
|
+
resInner.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
992
|
+
resInner.setHeader("Content-Disposition", `attachment; filename="chain-diagnostics-${chainId}-${Date.now()}.json"`);
|
|
993
|
+
resInner.status(200).send(`${JSON.stringify(bundle, null, 2)}\n`);
|
|
994
|
+
} catch (err) {
|
|
995
|
+
resInner.status(500).json({
|
|
996
|
+
code: "INTERNAL_ERROR",
|
|
997
|
+
error: err instanceof Error ? err.message : String(err)
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
});
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
1003
|
+
next();
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* Built-in Zero-Dependency Unified Chain Console (Clear-Trust Explorer + Node Status Dashboard +
|
|
1008
|
+
* Network/Consensus Health + Storage/DA + Auxiliary Config Manager + Maintenance Operations).
|
|
1009
|
+
*
|
|
1010
|
+
* Uses strict CSP (`script-src 'self'; object-src 'none'; frame-ancestors 'none'`),
|
|
1011
|
+
* `sessionStorage`-only admin token, and `textContent`-only DOM construction.
|
|
1012
|
+
*/
|
|
1013
|
+
function escapeHtmlAttr(value) {
|
|
1014
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">");
|
|
1015
|
+
}
|
|
1016
|
+
function sanitizeBasePath(rawBasePath) {
|
|
1017
|
+
const trimmed = String(rawBasePath || "").trim();
|
|
1018
|
+
if (!trimmed || trimmed === "/") return "";
|
|
1019
|
+
const cleaned = `/${trimmed.replace(/^\/+|\/+$/g, "")}`;
|
|
1020
|
+
if (!/^(\/[A-Za-z0-9._~%-]+)+$/.test(cleaned)) throw new Error(`Unsafe console appBasePath: ${rawBasePath}`);
|
|
1021
|
+
return cleaned;
|
|
1022
|
+
}
|
|
1023
|
+
function buildUnifiedConsoleHtml(options) {
|
|
1024
|
+
const base = escapeHtmlAttr(sanitizeBasePath(options.appBasePath));
|
|
1025
|
+
return `<!doctype html>
|
|
1026
|
+
<html lang="en">
|
|
1027
|
+
<head>
|
|
1028
|
+
<meta charset="utf-8" />
|
|
1029
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
1030
|
+
<title>ARC Chain Console — Status Dashboard & ARC Local Chain Explorer</title>
|
|
1031
|
+
<style>
|
|
1032
|
+
:root {
|
|
1033
|
+
color-scheme: dark;
|
|
1034
|
+
--bg: #080d1a;
|
|
1035
|
+
--panel: #11192e;
|
|
1036
|
+
--panel-alt: #16213d;
|
|
1037
|
+
--border: #233259;
|
|
1038
|
+
--text: #e8eefc;
|
|
1039
|
+
--muted: #93a3c8;
|
|
1040
|
+
--ok: #10b981;
|
|
1041
|
+
--warn: #f59e0b;
|
|
1042
|
+
--err: #ef4444;
|
|
1043
|
+
--accent: #38bdf8;
|
|
1044
|
+
--accent-dim: rgba(56, 189, 248, 0.14);
|
|
1045
|
+
}
|
|
1046
|
+
* { box-sizing: border-box; }
|
|
1047
|
+
body {
|
|
1048
|
+
margin: 0;
|
|
1049
|
+
font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
|
1050
|
+
background: var(--bg);
|
|
1051
|
+
color: var(--text);
|
|
1052
|
+
line-height: 1.45;
|
|
1053
|
+
}
|
|
1054
|
+
header {
|
|
1055
|
+
padding: 14px 24px;
|
|
1056
|
+
border-bottom: 1px solid var(--border);
|
|
1057
|
+
background: var(--panel);
|
|
1058
|
+
display: flex;
|
|
1059
|
+
flex-wrap: wrap;
|
|
1060
|
+
align-items: center;
|
|
1061
|
+
justify-content: space-between;
|
|
1062
|
+
gap: 12px;
|
|
1063
|
+
}
|
|
1064
|
+
.title { font-size: 18px; font-weight: 700; letter-spacing: 0.2px; }
|
|
1065
|
+
.subtitle { font-size: 12px; color: var(--muted); margin-top: 2px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
1066
|
+
.top-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
|
1067
|
+
.badge {
|
|
1068
|
+
padding: 5px 11px;
|
|
1069
|
+
border-radius: 999px;
|
|
1070
|
+
font-size: 11px;
|
|
1071
|
+
font-weight: 700;
|
|
1072
|
+
border: 1px solid transparent;
|
|
1073
|
+
display: inline-flex;
|
|
1074
|
+
align-items: center;
|
|
1075
|
+
gap: 6px;
|
|
1076
|
+
}
|
|
1077
|
+
.badge.ok { background: rgba(16, 185, 129, 0.15); color: #34d399; border-color: rgba(16, 185, 129, 0.4); }
|
|
1078
|
+
.badge.warn { background: rgba(245, 158, 11, 0.15); color: #fbbf24; border-color: rgba(245, 158, 11, 0.4); }
|
|
1079
|
+
.badge.err { background: rgba(239, 68, 68, 0.18); color: #f87171; border-color: rgba(239, 68, 68, 0.45); }
|
|
1080
|
+
.badge.info { background: var(--accent-dim); color: var(--accent); border-color: rgba(56, 189, 248, 0.35); }
|
|
1081
|
+
nav.tabs {
|
|
1082
|
+
display: flex;
|
|
1083
|
+
flex-wrap: wrap;
|
|
1084
|
+
gap: 6px;
|
|
1085
|
+
padding: 10px 24px;
|
|
1086
|
+
background: #0d1426;
|
|
1087
|
+
border-bottom: 1px solid var(--border);
|
|
1088
|
+
}
|
|
1089
|
+
.tab-btn {
|
|
1090
|
+
background: transparent;
|
|
1091
|
+
color: var(--muted);
|
|
1092
|
+
border: 1px solid transparent;
|
|
1093
|
+
border-radius: 8px;
|
|
1094
|
+
padding: 7px 14px;
|
|
1095
|
+
font-size: 13px;
|
|
1096
|
+
font-weight: 600;
|
|
1097
|
+
cursor: pointer;
|
|
1098
|
+
}
|
|
1099
|
+
.tab-btn:hover { color: var(--text); background: var(--panel); }
|
|
1100
|
+
.tab-btn.active {
|
|
1101
|
+
color: var(--accent);
|
|
1102
|
+
background: var(--accent-dim);
|
|
1103
|
+
border-color: rgba(56, 189, 248, 0.4);
|
|
1104
|
+
}
|
|
1105
|
+
main { max-width: 1320px; margin: 0 auto; padding: 20px 24px 56px; }
|
|
1106
|
+
.grid {
|
|
1107
|
+
display: grid;
|
|
1108
|
+
grid-template-columns: repeat(auto-fit, minmax(225px, 1fr));
|
|
1109
|
+
gap: 12px;
|
|
1110
|
+
margin-bottom: 18px;
|
|
1111
|
+
}
|
|
1112
|
+
.grid-2 {
|
|
1113
|
+
display: grid;
|
|
1114
|
+
grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
|
|
1115
|
+
gap: 14px;
|
|
1116
|
+
margin-bottom: 18px;
|
|
1117
|
+
}
|
|
1118
|
+
.card {
|
|
1119
|
+
background: var(--panel);
|
|
1120
|
+
border: 1px solid var(--border);
|
|
1121
|
+
border-radius: 10px;
|
|
1122
|
+
padding: 14px 16px;
|
|
1123
|
+
margin-bottom: 14px;
|
|
1124
|
+
}
|
|
1125
|
+
.grid .card, .grid-2 .card { margin-bottom: 0; }
|
|
1126
|
+
.section-title { font-size: 14px; font-weight: 700; margin: 0 0 10px 0; color: var(--text); }
|
|
1127
|
+
.label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.6px; color: var(--muted); }
|
|
1128
|
+
.value {
|
|
1129
|
+
margin-top: 6px;
|
|
1130
|
+
font-size: 14px;
|
|
1131
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
1132
|
+
word-break: break-all;
|
|
1133
|
+
}
|
|
1134
|
+
.value.lg { font-size: 20px; font-weight: 700; }
|
|
1135
|
+
.sub-value { margin-top: 4px; font-size: 12px; color: var(--muted); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
1136
|
+
.row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 12px; }
|
|
1137
|
+
input, select {
|
|
1138
|
+
background: #0b1224;
|
|
1139
|
+
border: 1px solid var(--border);
|
|
1140
|
+
border-radius: 8px;
|
|
1141
|
+
color: var(--text);
|
|
1142
|
+
padding: 8px 11px;
|
|
1143
|
+
font-size: 13px;
|
|
1144
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
1145
|
+
}
|
|
1146
|
+
input.grow { flex: 1; min-width: 200px; }
|
|
1147
|
+
button {
|
|
1148
|
+
background: var(--accent);
|
|
1149
|
+
color: #061224;
|
|
1150
|
+
border: 0;
|
|
1151
|
+
border-radius: 8px;
|
|
1152
|
+
padding: 8px 14px;
|
|
1153
|
+
font-size: 13px;
|
|
1154
|
+
font-weight: 700;
|
|
1155
|
+
cursor: pointer;
|
|
1156
|
+
}
|
|
1157
|
+
button.secondary {
|
|
1158
|
+
background: var(--panel-alt);
|
|
1159
|
+
color: var(--text);
|
|
1160
|
+
border: 1px solid var(--border);
|
|
1161
|
+
}
|
|
1162
|
+
button.danger {
|
|
1163
|
+
background: rgba(239, 68, 68, 0.2);
|
|
1164
|
+
color: #fca5a5;
|
|
1165
|
+
border: 1px solid rgba(239, 68, 68, 0.45);
|
|
1166
|
+
}
|
|
1167
|
+
button:disabled { opacity: 0.45; cursor: not-allowed; }
|
|
1168
|
+
table {
|
|
1169
|
+
width: 100%;
|
|
1170
|
+
border-collapse: collapse;
|
|
1171
|
+
background: var(--panel);
|
|
1172
|
+
border: 1px solid var(--border);
|
|
1173
|
+
border-radius: 10px;
|
|
1174
|
+
overflow: hidden;
|
|
1175
|
+
}
|
|
1176
|
+
th, td {
|
|
1177
|
+
text-align: left;
|
|
1178
|
+
padding: 9px 11px;
|
|
1179
|
+
border-bottom: 1px solid var(--border);
|
|
1180
|
+
font-size: 12px;
|
|
1181
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
1182
|
+
word-break: break-all;
|
|
1183
|
+
}
|
|
1184
|
+
th { color: var(--muted); font-weight: 600; background: #0e162b; }
|
|
1185
|
+
pre {
|
|
1186
|
+
background: #0a1020;
|
|
1187
|
+
border: 1px solid var(--border);
|
|
1188
|
+
border-radius: 10px;
|
|
1189
|
+
padding: 12px;
|
|
1190
|
+
overflow-x: auto;
|
|
1191
|
+
font-size: 12px;
|
|
1192
|
+
margin: 10px 0;
|
|
1193
|
+
}
|
|
1194
|
+
.banner {
|
|
1195
|
+
padding: 10px 14px;
|
|
1196
|
+
border-radius: 8px;
|
|
1197
|
+
margin-bottom: 14px;
|
|
1198
|
+
font-size: 13px;
|
|
1199
|
+
border: 1px solid var(--border);
|
|
1200
|
+
background: var(--panel-alt);
|
|
1201
|
+
}
|
|
1202
|
+
.banner.err { border-color: rgba(239, 68, 68, 0.5); color: #fca5a5; background: rgba(239, 68, 68, 0.12); }
|
|
1203
|
+
.banner.ok { border-color: rgba(16, 185, 129, 0.45); color: #6ee7b7; background: rgba(16, 185, 129, 0.12); }
|
|
1204
|
+
.form-grid {
|
|
1205
|
+
display: grid;
|
|
1206
|
+
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
|
|
1207
|
+
gap: 10px;
|
|
1208
|
+
margin-bottom: 12px;
|
|
1209
|
+
}
|
|
1210
|
+
.field label { display: block; font-size: 11px; color: var(--muted); margin-bottom: 4px; text-transform: uppercase; }
|
|
1211
|
+
.field input, .field select { width: 100%; }
|
|
1212
|
+
.hidden { display: none !important; }
|
|
1213
|
+
.clickable { color: var(--accent); cursor: pointer; text-decoration: underline; }
|
|
1214
|
+
</style>
|
|
1215
|
+
</head>
|
|
1216
|
+
<body data-default-tab="${options.defaultTab === "explorer" ? "explorer" : "overview"}" data-base-path="${base}">
|
|
1217
|
+
<header>
|
|
1218
|
+
<div>
|
|
1219
|
+
<div class="title" id="chain-title">ARC Unified Chain Console</div>
|
|
1220
|
+
<div class="subtitle" id="chain-subtitle">Connecting to local node telemetry & Clear-Trust verifier...</div>
|
|
1221
|
+
</div>
|
|
1222
|
+
<div class="top-controls">
|
|
1223
|
+
<span id="role-badge" class="badge info">ROLE: -</span>
|
|
1224
|
+
<div id="trust-badge" class="badge warn">CHECKING STATUS</div>
|
|
1225
|
+
<button id="auto-refresh-btn" type="button" class="secondary">Auto: 5s</button>
|
|
1226
|
+
<button id="refresh-btn" type="button" class="secondary">Refresh</button>
|
|
1227
|
+
<button id="auth-toggle-btn" type="button" class="secondary">Admin Unlock</button>
|
|
1228
|
+
</div>
|
|
1229
|
+
</header>
|
|
1230
|
+
|
|
1231
|
+
<div id="auth-bar" class="banner hidden" style="margin: 12px 24px 0;">
|
|
1232
|
+
<div class="row" style="margin-bottom: 0;">
|
|
1233
|
+
<span class="label">Admin Token (sessionStorage only):</span>
|
|
1234
|
+
<input id="admin-token-input" type="password" class="grow" placeholder="Enter CHAIN_ADMIN_TOKEN or Bearer secret..." autocomplete="off" />
|
|
1235
|
+
<button id="admin-save-btn" type="button">Unlock Session</button>
|
|
1236
|
+
<button id="admin-clear-btn" type="button" class="danger">Lock / Clear</button>
|
|
1237
|
+
</div>
|
|
1238
|
+
</div>
|
|
1239
|
+
|
|
1240
|
+
<nav class="tabs" role="tablist">
|
|
1241
|
+
<button class="tab-btn" data-tab="overview" type="button">Status & Health</button>
|
|
1242
|
+
<button class="tab-btn" data-tab="explorer" type="button">Local Explorer</button>
|
|
1243
|
+
<button class="tab-btn" data-tab="network" type="button">Consensus & Peers</button>
|
|
1244
|
+
<button class="tab-btn" data-tab="storage" type="button">Storage & DA</button>
|
|
1245
|
+
<button class="tab-btn" data-tab="config" type="button">Auxiliary Config</button>
|
|
1246
|
+
<button class="tab-btn" data-tab="ops" type="button">Operations</button>
|
|
1247
|
+
</nav>
|
|
1248
|
+
|
|
1249
|
+
<main>
|
|
1250
|
+
<div id="global-notice" class="banner hidden"></div>
|
|
1251
|
+
|
|
1252
|
+
<!-- Shared Top Clear-Trust Summary Strip (Always visible for instant node awareness & #1710 compatibility) -->
|
|
1253
|
+
<section class="grid">
|
|
1254
|
+
<div class="card">
|
|
1255
|
+
<div class="label">Node Role / Write Policy</div>
|
|
1256
|
+
<div class="value" id="m-role">-</div>
|
|
1257
|
+
<div class="sub-value" id="m-consensus">-</div>
|
|
1258
|
+
</div>
|
|
1259
|
+
<div class="card">
|
|
1260
|
+
<div class="label">Local / Upstream Sequence</div>
|
|
1261
|
+
<div class="value" id="m-seq">-</div>
|
|
1262
|
+
<div class="sub-value" id="m-lag">-</div>
|
|
1263
|
+
</div>
|
|
1264
|
+
<div class="card">
|
|
1265
|
+
<div class="label">Verified Checkpoint</div>
|
|
1266
|
+
<div class="value" id="m-cp">-</div>
|
|
1267
|
+
<div class="sub-value" id="m-cp-age">-</div>
|
|
1268
|
+
</div>
|
|
1269
|
+
<div class="card">
|
|
1270
|
+
<div class="label">Local State Commit Hash</div>
|
|
1271
|
+
<div class="value" id="m-commit">-</div>
|
|
1272
|
+
<div class="sub-value" id="m-uptime">-</div>
|
|
1273
|
+
</div>
|
|
1274
|
+
</section>
|
|
1275
|
+
|
|
1276
|
+
<!-- TAB 1: Overview & Health -->
|
|
1277
|
+
<section id="tab-overview" class="tab-panel">
|
|
1278
|
+
<div class="grid">
|
|
1279
|
+
<div class="card">
|
|
1280
|
+
<div class="label">Throughput (60s Rolling)</div>
|
|
1281
|
+
<div class="value lg" id="ov-tps">0.00 TPS</div>
|
|
1282
|
+
<div class="sub-value" id="ov-tx-totals">-</div>
|
|
1283
|
+
</div>
|
|
1284
|
+
<div class="card">
|
|
1285
|
+
<div class="label">Execution Queue & Pre-Flight</div>
|
|
1286
|
+
<div class="value lg" id="ov-queue">0 / 200</div>
|
|
1287
|
+
<div class="sub-value" id="ov-preflight">-</div>
|
|
1288
|
+
</div>
|
|
1289
|
+
<div class="card">
|
|
1290
|
+
<div class="label">SQLite Footprint (4 DBs)</div>
|
|
1291
|
+
<div class="value lg" id="ov-sqlite-bytes">-</div>
|
|
1292
|
+
<div class="sub-value" id="ov-wal-bytes">-</div>
|
|
1293
|
+
</div>
|
|
1294
|
+
<div class="card">
|
|
1295
|
+
<div class="label">Memory & Runtime</div>
|
|
1296
|
+
<div class="value lg" id="ov-mem">-</div>
|
|
1297
|
+
<div class="sub-value" id="ov-Lists">-</div>
|
|
1298
|
+
</div>
|
|
1299
|
+
</div>
|
|
1300
|
+
|
|
1301
|
+
<div class="grid-2">
|
|
1302
|
+
<div class="card">
|
|
1303
|
+
<h3 class="section-title">Ledger & Checkpoint Health</h3>
|
|
1304
|
+
<div id="ov-ledger-health" class="value">-</div>
|
|
1305
|
+
<div id="ov-ledger-thresholds" class="sub-value" style="margin-top: 8px;">-</div>
|
|
1306
|
+
</div>
|
|
1307
|
+
<div class="card">
|
|
1308
|
+
<h3 class="section-title">Gas Security Guard (Pre-Queue Admission)</h3>
|
|
1309
|
+
<div id="ov-gas-guard" class="value">-</div>
|
|
1310
|
+
<div id="ov-gas-guard-sub" class="sub-value" style="margin-top: 8px;">-</div>
|
|
1311
|
+
</div>
|
|
1312
|
+
</div>
|
|
1313
|
+
</section>
|
|
1314
|
+
|
|
1315
|
+
<!-- TAB 2: Clear-Trust Local Explorer -->
|
|
1316
|
+
<section id="tab-explorer" class="tab-panel hidden">
|
|
1317
|
+
<div class="row">
|
|
1318
|
+
<input id="lookup-input" class="grow" type="text" placeholder="Inspect 64-hex tx hash (with Merkle proof) or account DID..." />
|
|
1319
|
+
<button id="lookup-btn" type="button">Inspect & Verify</button>
|
|
1320
|
+
</div>
|
|
1321
|
+
<pre id="inspect-output" class="hidden"></pre>
|
|
1322
|
+
<div class="card">
|
|
1323
|
+
<div class="section-title">Recent Local Indexed Transactions (Click Hash to Verify Proof)</div>
|
|
1324
|
+
<table>
|
|
1325
|
+
<thead>
|
|
1326
|
+
<tr><th>Hash</th><th>Type</th><th>Code</th><th>Sender</th><th>Time</th></tr>
|
|
1327
|
+
</thead>
|
|
1328
|
+
<tbody id="tx-tbody"></tbody>
|
|
1329
|
+
</table>
|
|
1330
|
+
</div>
|
|
1331
|
+
</section>
|
|
1332
|
+
|
|
1333
|
+
<!-- TAB 3: Consensus & Network Peers -->
|
|
1334
|
+
<section id="tab-network" class="tab-panel hidden">
|
|
1335
|
+
<div class="grid">
|
|
1336
|
+
<div class="card"><div class="label">Consensus Mode / View</div><div class="value" id="net-view">-</div></div>
|
|
1337
|
+
<div class="card"><div class="label">HighQC / LockedQC</div><div class="value" id="net-qc">-</div></div>
|
|
1338
|
+
<div class="card"><div class="label">Witness Quorum & Circuit</div><div class="value" id="net-witness">-</div></div>
|
|
1339
|
+
<div class="card"><div class="label">Proposer Identity</div><div class="value" id="net-proposer">-</div></div>
|
|
1340
|
+
</div>
|
|
1341
|
+
|
|
1342
|
+
<div class="card">
|
|
1343
|
+
<div class="section-title">HotStuff BFT Validator Roster</div>
|
|
1344
|
+
<table>
|
|
1345
|
+
<thead>
|
|
1346
|
+
<tr><th>Validator DID</th><th>Role</th><th>Reachable</th><th>Last Seen</th><th>Send Failures</th><th>Wire Endpoint</th></tr>
|
|
1347
|
+
</thead>
|
|
1348
|
+
<tbody id="validators-tbody"></tbody>
|
|
1349
|
+
</table>
|
|
1350
|
+
</div>
|
|
1351
|
+
|
|
1352
|
+
<div class="card">
|
|
1353
|
+
<div class="section-title">Follower Upstream LeaderRouter Candidates</div>
|
|
1354
|
+
<table>
|
|
1355
|
+
<thead>
|
|
1356
|
+
<tr><th>Candidate</th><th>Reachable</th><th>RTT</th><th>Upstream Seq</th><th>Checkpoint</th><th>Last Error</th></tr>
|
|
1357
|
+
</thead>
|
|
1358
|
+
<tbody id="peers-tbody"></tbody>
|
|
1359
|
+
</table>
|
|
1360
|
+
</div>
|
|
1361
|
+
</section>
|
|
1362
|
+
|
|
1363
|
+
<!-- TAB 4: Storage & DA -->
|
|
1364
|
+
<section id="tab-storage" class="tab-panel hidden">
|
|
1365
|
+
<div class="grid">
|
|
1366
|
+
<div class="card"><div class="label">Retention Mode</div><div class="value" id="st-retention">-</div></div>
|
|
1367
|
+
<div class="card"><div class="label">Cold Snapshot Base URL</div><div class="value" id="st-snapshot">-</div></div>
|
|
1368
|
+
<div class="card"><div class="label">Latest L1 Anchor Receipt</div><div class="value" id="st-anchor">-</div></div>
|
|
1369
|
+
<div class="card"><div class="label">EntryHash v2 From</div><div class="value" id="st-v2from">-</div></div>
|
|
1370
|
+
</div>
|
|
1371
|
+
|
|
1372
|
+
<div class="card">
|
|
1373
|
+
<div class="section-title">SQLite Database Files & WAL Sidecars (15s Coalesced Cache)</div>
|
|
1374
|
+
<table>
|
|
1375
|
+
<thead>
|
|
1376
|
+
<tr><th>Database</th><th>File</th><th>Main Size</th><th>WAL Size</th><th>SHM Size</th><th>Total</th><th>Status</th></tr>
|
|
1377
|
+
</thead>
|
|
1378
|
+
<tbody id="db-tbody"></tbody>
|
|
1379
|
+
</table>
|
|
1380
|
+
</div>
|
|
1381
|
+
|
|
1382
|
+
<div class="card">
|
|
1383
|
+
<div class="section-title">Indexed Entity Counts</div>
|
|
1384
|
+
<div class="grid" id="entity-counts-grid"></div>
|
|
1385
|
+
</div>
|
|
1386
|
+
</section>
|
|
1387
|
+
|
|
1388
|
+
<!-- TAB 5: Auxiliary Configuration Manager -->
|
|
1389
|
+
<section id="tab-config" class="tab-panel hidden">
|
|
1390
|
+
<div id="cfg-auth-hint" class="banner">Unlock Admin Session above to view and hot-reload node preferences.</div>
|
|
1391
|
+
|
|
1392
|
+
<div id="cfg-editor" class="hidden">
|
|
1393
|
+
<div class="card">
|
|
1394
|
+
<div class="section-title">Operational & Health Runtime Parameters (Hot-Reload)</div>
|
|
1395
|
+
<div class="form-grid">
|
|
1396
|
+
<div class="field">
|
|
1397
|
+
<label for="cfg-write-policy">Write Policy</label>
|
|
1398
|
+
<select id="cfg-write-policy">
|
|
1399
|
+
<option value="reject">reject</option>
|
|
1400
|
+
<option value="forward">forward</option>
|
|
1401
|
+
</select>
|
|
1402
|
+
</div>
|
|
1403
|
+
<div class="field">
|
|
1404
|
+
<label for="cfg-tx-max">Max Queued Tx Requests</label>
|
|
1405
|
+
<input id="cfg-tx-max" type="number" min="1" max="10000" />
|
|
1406
|
+
</div>
|
|
1407
|
+
<div class="field">
|
|
1408
|
+
<label for="cfg-poll-ms">Follower Poll Interval (ms)</label>
|
|
1409
|
+
<input id="cfg-poll-ms" type="number" min="100" max="300000" />
|
|
1410
|
+
</div>
|
|
1411
|
+
<div class="field">
|
|
1412
|
+
<label for="cfg-max-lag">Follower Max Sync Lag</label>
|
|
1413
|
+
<input id="cfg-max-lag" type="number" min="0" max="1000000" />
|
|
1414
|
+
</div>
|
|
1415
|
+
<div class="field">
|
|
1416
|
+
<label for="cfg-hl-lag">Health Max Checkpoint Lag</label>
|
|
1417
|
+
<input id="cfg-hl-lag" type="number" min="1" max="1000000" />
|
|
1418
|
+
</div>
|
|
1419
|
+
<div class="field">
|
|
1420
|
+
<label for="cfg-hl-age">Health Max Checkpoint Age (ms)</label>
|
|
1421
|
+
<input id="cfg-hl-age" type="number" min="1000" max="86400000" />
|
|
1422
|
+
</div>
|
|
1423
|
+
<div class="field">
|
|
1424
|
+
<label for="cfg-hl-unfin">Health Max Unfinalized Age (ms)</label>
|
|
1425
|
+
<input id="cfg-hl-unfin" type="number" min="1000" max="86400000" />
|
|
1426
|
+
</div>
|
|
1427
|
+
</div>
|
|
1428
|
+
<div class="field" id="cfg-peers-wrap" style="margin-bottom: 12px;">
|
|
1429
|
+
<label for="cfg-peer-urls">Follower Upstream Peer URLs (comma-separated HTTP/HTTPS)</label>
|
|
1430
|
+
<input id="cfg-peer-urls" type="text" placeholder="https://validator-1.example.com, https://validator-2.example.com" />
|
|
1431
|
+
</div>
|
|
1432
|
+
<button id="cfg-save-runtime-btn" type="button">Save & Hot-Apply Runtime Config</button>
|
|
1433
|
+
</div>
|
|
1434
|
+
|
|
1435
|
+
<div class="card">
|
|
1436
|
+
<div class="section-title">Blocked Accounts (Pre-Queue RPC Admission & /blocked)</div>
|
|
1437
|
+
<div class="row">
|
|
1438
|
+
<input id="add-blocked-addr" class="grow" type="text" placeholder="Account DID or 0x address..." />
|
|
1439
|
+
<input id="add-blocked-memo" type="text" placeholder="Optional memo..." />
|
|
1440
|
+
<button id="add-blocked-btn" type="button">Add & Save</button>
|
|
1441
|
+
</div>
|
|
1442
|
+
<table>
|
|
1443
|
+
<thead><tr><th>Address</th><th>Memo</th><th>Source</th><th>Action</th></tr></thead>
|
|
1444
|
+
<tbody id="cfg-blocked-tbody"></tbody>
|
|
1445
|
+
</table>
|
|
1446
|
+
</div>
|
|
1447
|
+
|
|
1448
|
+
<div class="card">
|
|
1449
|
+
<div class="section-title">Trusted Accounts (Token-Flow Risk Tolerance)</div>
|
|
1450
|
+
<div class="row">
|
|
1451
|
+
<input id="add-trusted-addr" class="grow" type="text" placeholder="Account DID..." />
|
|
1452
|
+
<input id="add-trusted-tol" type="number" min="0" max="1000000000" placeholder="Tolerance (0)" />
|
|
1453
|
+
<input id="add-trusted-memo" type="text" placeholder="Optional memo..." />
|
|
1454
|
+
<button id="add-trusted-btn" type="button">Add & Save</button>
|
|
1455
|
+
</div>
|
|
1456
|
+
<table>
|
|
1457
|
+
<thead><tr><th>Address</th><th>Tolerance</th><th>Memo</th><th>Source</th><th>Action</th></tr></thead>
|
|
1458
|
+
<tbody id="cfg-trusted-tbody"></tbody>
|
|
1459
|
+
</table>
|
|
1460
|
+
</div>
|
|
1461
|
+
|
|
1462
|
+
<div class="card">
|
|
1463
|
+
<div class="section-title">Reserved Token Symbols</div>
|
|
1464
|
+
<div id="cfg-symbols-lock-msg" class="sub-value" style="margin-bottom: 8px;"></div>
|
|
1465
|
+
<div class="row" id="add-symbol-row">
|
|
1466
|
+
<input id="add-symbol-val" type="text" placeholder="SYMBOL (A-Z0-9_)" />
|
|
1467
|
+
<input id="add-symbol-memo" class="grow" type="text" placeholder="Optional memo..." />
|
|
1468
|
+
<button id="add-symbol-btn" type="button">Add & Save</button>
|
|
1469
|
+
</div>
|
|
1470
|
+
<table>
|
|
1471
|
+
<thead><tr><th>Symbol</th><th>Memo</th><th>Source</th><th>Action</th></tr></thead>
|
|
1472
|
+
<tbody id="cfg-symbols-tbody"></tbody>
|
|
1473
|
+
</table>
|
|
1474
|
+
</div>
|
|
1475
|
+
</div>
|
|
1476
|
+
</section>
|
|
1477
|
+
|
|
1478
|
+
<!-- TAB 6: Maintenance Operations & Diagnostics -->
|
|
1479
|
+
<section id="tab-ops" class="tab-panel hidden">
|
|
1480
|
+
<div class="grid-2">
|
|
1481
|
+
<div class="card">
|
|
1482
|
+
<h3 class="section-title">Sync, Preferences & Anti-Replay Persistence</h3>
|
|
1483
|
+
<div class="row">
|
|
1484
|
+
<button id="act-sync-btn" type="button">Trigger Sync / Leader Probe Now</button>
|
|
1485
|
+
<button id="act-reload-prefs-btn" type="button" class="secondary">Reload preferences.json</button>
|
|
1486
|
+
<button id="act-persist-filter-btn" type="button" class="secondary">Flush Anti-Replay Filter</button>
|
|
1487
|
+
</div>
|
|
1488
|
+
<div id="ops-sync-meta" class="sub-value">-</div>
|
|
1489
|
+
</div>
|
|
1490
|
+
|
|
1491
|
+
<div class="card">
|
|
1492
|
+
<h3 class="section-title">IndexDB Prune & Token Distribution</h3>
|
|
1493
|
+
<div class="row">
|
|
1494
|
+
<button id="act-prune-dry-btn" type="button" class="secondary">IndexDB Prune (Dry-Run)</button>
|
|
1495
|
+
<button id="act-prune-run-btn" type="button" class="danger">IndexDB Prune (Execute)</button>
|
|
1496
|
+
</div>
|
|
1497
|
+
<div class="row">
|
|
1498
|
+
<input id="act-dist-token" class="grow" type="text" placeholder="Optional token DID for distribution..." />
|
|
1499
|
+
<button id="act-dist-btn" type="button" class="secondary">Update Token Distribution</button>
|
|
1500
|
+
</div>
|
|
1501
|
+
<div id="ops-maint-meta" class="sub-value">-</div>
|
|
1502
|
+
</div>
|
|
1503
|
+
</div>
|
|
1504
|
+
|
|
1505
|
+
<div class="card">
|
|
1506
|
+
<h3 class="section-title">Sanitized Diagnostics Bundle</h3>
|
|
1507
|
+
<div class="row">
|
|
1508
|
+
<button id="act-diag-btn" type="button">Download Diagnostics JSON</button>
|
|
1509
|
+
</div>
|
|
1510
|
+
<pre id="ops-output" class="hidden"></pre>
|
|
1511
|
+
</div>
|
|
1512
|
+
</section>
|
|
1513
|
+
</main>
|
|
1514
|
+
|
|
1515
|
+
<script src="/__blocklet__.js"><\/script>
|
|
1516
|
+
<script src="/static/js/networks.js"><\/script>
|
|
1517
|
+
<script src="${base}/app.js"><\/script>
|
|
1518
|
+
</body>
|
|
1519
|
+
</html>
|
|
1520
|
+
`;
|
|
1521
|
+
}
|
|
1522
|
+
const UNIFIED_CONSOLE_APP_JS = `(function () {
|
|
1523
|
+
'use strict';
|
|
1524
|
+
|
|
1525
|
+
var TOKEN_STORAGE_KEY = 'ocap_chain_admin_token';
|
|
1526
|
+
var endpoint = (
|
|
1527
|
+
(window.blocklet && window.blocklet.env && (window.blocklet.env.CHAIN_API_ENDPOINT || window.blocklet.env.EXPLORER_CHAIN_ENDPOINT)) ||
|
|
1528
|
+
'/api'
|
|
1529
|
+
).replace(/\\/+$/g, '') || '/api';
|
|
1530
|
+
|
|
1531
|
+
var activeTab = document.body.getAttribute('data-default-tab') || 'overview';
|
|
1532
|
+
var autoRefreshTimer = null;
|
|
1533
|
+
var autoRefreshEnabled = true;
|
|
1534
|
+
var currentConfigState = null;
|
|
1535
|
+
var currentCapabilities = null;
|
|
1536
|
+
|
|
1537
|
+
function getAdminToken() {
|
|
1538
|
+
try {
|
|
1539
|
+
return window.sessionStorage.getItem(TOKEN_STORAGE_KEY) || '';
|
|
1540
|
+
} catch (_e) {
|
|
1541
|
+
return '';
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
function setAdminToken(tok) {
|
|
1546
|
+
try {
|
|
1547
|
+
if (tok) {
|
|
1548
|
+
window.sessionStorage.setItem(TOKEN_STORAGE_KEY, tok);
|
|
1549
|
+
} else {
|
|
1550
|
+
window.sessionStorage.removeItem(TOKEN_STORAGE_KEY);
|
|
1551
|
+
}
|
|
1552
|
+
} catch (_e) {}
|
|
1553
|
+
updateAuthUi();
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
function buildHeaders(isJsonBody) {
|
|
1557
|
+
var h = { Accept: 'application/json', 'X-Requested-With': 'ChainConsole' };
|
|
1558
|
+
if (isJsonBody) {
|
|
1559
|
+
h['Content-Type'] = 'application/json';
|
|
1560
|
+
}
|
|
1561
|
+
var tok = getAdminToken();
|
|
1562
|
+
if (tok) {
|
|
1563
|
+
h['X-Chain-Admin-Token'] = tok;
|
|
1564
|
+
}
|
|
1565
|
+
return h;
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
function setText(id, value) {
|
|
1569
|
+
var el = document.getElementById(id);
|
|
1570
|
+
if (el) el.textContent = value == null ? '-' : String(value);
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
function formatBytes(bytes) {
|
|
1574
|
+
var n = Number(bytes || 0);
|
|
1575
|
+
if (!isFinite(n) || n <= 0) return '0 B';
|
|
1576
|
+
var units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
|
|
1577
|
+
var idx = Math.min(units.length - 1, Math.floor(Math.log(n) / Math.log(1024)));
|
|
1578
|
+
var val = n / Math.pow(1024, idx);
|
|
1579
|
+
return (idx === 0 ? String(Math.round(val)) : val.toFixed(2)) + ' ' + units[idx];
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
function showNotice(msg, kind) {
|
|
1583
|
+
var el = document.getElementById('global-notice');
|
|
1584
|
+
if (!el) return;
|
|
1585
|
+
if (!msg) {
|
|
1586
|
+
el.className = 'banner hidden';
|
|
1587
|
+
el.textContent = '';
|
|
1588
|
+
return;
|
|
1589
|
+
}
|
|
1590
|
+
el.className = 'banner ' + (kind === 'err' ? 'err' : kind === 'ok' ? 'ok' : '');
|
|
1591
|
+
el.textContent = String(msg);
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
function clearChildren(el) {
|
|
1595
|
+
while (el && el.firstChild) {
|
|
1596
|
+
el.removeChild(el.firstChild);
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
function appendRow(tbody, cells) {
|
|
1601
|
+
if (!tbody) return;
|
|
1602
|
+
var tr = document.createElement('tr');
|
|
1603
|
+
for (var i = 0; i < cells.length; i++) {
|
|
1604
|
+
var td = document.createElement('td');
|
|
1605
|
+
var cell = cells[i];
|
|
1606
|
+
if (cell && typeof cell === 'object' && cell.nodeType === 1) {
|
|
1607
|
+
td.appendChild(cell);
|
|
1608
|
+
} else {
|
|
1609
|
+
td.textContent = cell == null ? '-' : String(cell);
|
|
1610
|
+
}
|
|
1611
|
+
tr.appendChild(td);
|
|
1612
|
+
}
|
|
1613
|
+
tbody.appendChild(tr);
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
function switchTab(tabId) {
|
|
1617
|
+
activeTab = tabId;
|
|
1618
|
+
var btns = document.querySelectorAll('.tab-btn');
|
|
1619
|
+
for (var i = 0; i < btns.length; i++) {
|
|
1620
|
+
var b = btns[i];
|
|
1621
|
+
if (b.getAttribute('data-tab') === tabId) {
|
|
1622
|
+
b.classList.add('active');
|
|
1623
|
+
} else {
|
|
1624
|
+
b.classList.remove('active');
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
var panels = document.querySelectorAll('.tab-panel');
|
|
1628
|
+
for (var p = 0; p < panels.length; p++) {
|
|
1629
|
+
var panel = panels[p];
|
|
1630
|
+
if (panel.id === 'tab-' + tabId) {
|
|
1631
|
+
panel.classList.remove('hidden');
|
|
1632
|
+
} else {
|
|
1633
|
+
panel.classList.add('hidden');
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
if (tabId === 'config') {
|
|
1637
|
+
loadAdminConfig();
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
function updateAuthUi() {
|
|
1642
|
+
var tok = getAdminToken();
|
|
1643
|
+
var btn = document.getElementById('auth-toggle-btn');
|
|
1644
|
+
if (btn) {
|
|
1645
|
+
btn.textContent = tok ? 'Admin Unlocked' : 'Admin Unlock';
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
async function gql(query, variables) {
|
|
1650
|
+
var res = await fetch(endpoint, {
|
|
1651
|
+
method: 'POST',
|
|
1652
|
+
headers: buildHeaders(true),
|
|
1653
|
+
body: JSON.stringify({ query: query, variables: variables || {} })
|
|
1654
|
+
});
|
|
1655
|
+
return res.json();
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
async function refreshDashboard() {
|
|
1659
|
+
try {
|
|
1660
|
+
var dashRes = await fetch(endpoint + '/node/dashboard', { headers: buildHeaders(false) });
|
|
1661
|
+
if (dashRes.status === 401 || dashRes.status === 403) {
|
|
1662
|
+
await refreshFallbackFollowerStatus();
|
|
1663
|
+
showNotice('Dashboard requires admin authentication (DASHBOARD_REQUIRE_AUTH=1). Unlock session above.', 'err');
|
|
1664
|
+
return;
|
|
1665
|
+
}
|
|
1666
|
+
if (!dashRes.ok) {
|
|
1667
|
+
await refreshFallbackFollowerStatus();
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
var dash = await dashRes.json();
|
|
1671
|
+
renderDashboardData(dash);
|
|
1672
|
+
} catch (_err) {
|
|
1673
|
+
await refreshFallbackFollowerStatus();
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
if (activeTab === 'explorer') {
|
|
1677
|
+
await refreshRecentTransactions();
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
async function refreshFallbackFollowerStatus() {
|
|
1682
|
+
try {
|
|
1683
|
+
var statusRes = await fetch(endpoint + '/follower/status', { headers: { Accept: 'application/json' } });
|
|
1684
|
+
var status = await statusRes.json();
|
|
1685
|
+
var badge = document.getElementById('trust-badge');
|
|
1686
|
+
if (badge) {
|
|
1687
|
+
if (status.halted) {
|
|
1688
|
+
badge.className = 'badge err';
|
|
1689
|
+
badge.textContent = 'HALTED: ' + (status.haltReason || 'VERIFICATION MISMATCH');
|
|
1690
|
+
} else if (status.synced) {
|
|
1691
|
+
badge.className = 'badge ok';
|
|
1692
|
+
badge.textContent = status.nodeRole === 'validator' ? 'PRIMARY VALIDATOR (SYNCED)' : 'VERIFIED FOLLOWER (SYNCED)';
|
|
1693
|
+
} else {
|
|
1694
|
+
badge.className = 'badge warn';
|
|
1695
|
+
badge.textContent = 'CATCHING UP (LAG: ' + (status.syncLagEntries == null ? '?' : status.syncLagEntries) + ')';
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
setText('chain-title', 'ARC Unified Chain Console — ' + (status.chainId || 'chain'));
|
|
1699
|
+
setText('chain-subtitle', 'Sync Mode: ' + (status.syncMode || '-') + (status.activeLeaderUrl ? ' | Upstream: ' + status.activeLeaderUrl : ''));
|
|
1700
|
+
setText('m-role', (status.nodeRole || '-') + ' / ' + (status.writePolicy || '-'));
|
|
1701
|
+
setText('m-seq', String(status.localSequence ?? 0) + ' / ' + String(status.upstreamSequence == null ? status.localSequence ?? 0 : status.upstreamSequence));
|
|
1702
|
+
setText('m-cp', '#' + String(status.verifiedCheckpointHeight ?? 0) + (status.verifiedCheckpointHash ? ' (' + String(status.verifiedCheckpointHash).slice(0, 14) + '...)' : ''));
|
|
1703
|
+
setText('m-commit', status.localStateCommitHash || '-');
|
|
1704
|
+
} catch (err) {
|
|
1705
|
+
setText('chain-subtitle', 'Status check failed: ' + (err && err.message ? err.message : String(err)));
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
function renderDashboardData(dash) {
|
|
1710
|
+
var node = dash.node || {};
|
|
1711
|
+
var lh = dash.ledgerHealth || {};
|
|
1712
|
+
var pipe = dash.pipeline || {};
|
|
1713
|
+
var storage = dash.storage || {};
|
|
1714
|
+
var gas = dash.gasSecurity || {};
|
|
1715
|
+
var cons = dash.consensus || {};
|
|
1716
|
+
var da = dash.da || {};
|
|
1717
|
+
var res = dash.resources || {};
|
|
1718
|
+
var prefs = dash.preferencesSummary || {};
|
|
1719
|
+
var maint = dash.maintenance || {};
|
|
1720
|
+
|
|
1721
|
+
setText('chain-title', 'ARC Chain Console — ' + (node.chainId || 'chain') + ' (v' + (node.version || '-') + ')');
|
|
1722
|
+
setText(
|
|
1723
|
+
'chain-subtitle',
|
|
1724
|
+
'Mode: ' + (node.consensusMode || 'single') +
|
|
1725
|
+
' | Writable: ' + (node.writable ? 'yes' : 'no') +
|
|
1726
|
+
(node.activeLeaderUrl ? ' | Leader: ' + node.activeLeaderUrl : '')
|
|
1727
|
+
);
|
|
1728
|
+
|
|
1729
|
+
var roleBadge = document.getElementById('role-badge');
|
|
1730
|
+
if (roleBadge) {
|
|
1731
|
+
roleBadge.textContent = String(node.nodeRole || 'validator').toUpperCase() + ' (' + String(node.consensusMode || 'single').toUpperCase() + ')';
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
var badge = document.getElementById('trust-badge');
|
|
1735
|
+
if (badge) {
|
|
1736
|
+
if (node.halted) {
|
|
1737
|
+
badge.className = 'badge err';
|
|
1738
|
+
badge.textContent = 'HALTED: ' + (node.haltReason || 'FAIL-CLOSED');
|
|
1739
|
+
} else if (dash.overallStatus === 'healthy' && node.synced) {
|
|
1740
|
+
badge.className = 'badge ok';
|
|
1741
|
+
badge.textContent = node.nodeRole === 'validator' ? 'VALIDATOR HEALTHY (SYNCED)' : 'VERIFIED FOLLOWER (SYNCED)';
|
|
1742
|
+
} else {
|
|
1743
|
+
badge.className = 'badge warn';
|
|
1744
|
+
badge.textContent = !node.synced
|
|
1745
|
+
? 'CATCHING UP (LAG: ' + String(node.syncLagEntries ?? '?') + ')'
|
|
1746
|
+
: 'DEGRADED HEALTH';
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
setText('m-role', (node.nodeRole || '-') + ' / ' + (node.writePolicy || '-'));
|
|
1751
|
+
setText('m-consensus', 'Consensus: ' + (node.consensusMode || 'single') + (cons.view != null ? ' (View ' + cons.view + ')' : ''));
|
|
1752
|
+
setText('m-seq', String(node.localSequence ?? 0) + ' / ' + String(node.upstreamSequence ?? node.localSequence ?? 0));
|
|
1753
|
+
setText('m-lag', 'Sync Lag: ' + String(node.syncLagEntries ?? 0) + ' entries');
|
|
1754
|
+
setText(
|
|
1755
|
+
'm-cp',
|
|
1756
|
+
'#' + String(node.verifiedCheckpointHeight ?? 0) +
|
|
1757
|
+
(node.verifiedCheckpointHash ? ' (' + String(node.verifiedCheckpointHash).slice(0, 12) + '...)' : '')
|
|
1758
|
+
);
|
|
1759
|
+
setText('m-cp-age', 'CP Lag: ' + String(lh.checkpointLag ?? 0) + ' | Age: ' + (lh.checkpointAge || '0s'));
|
|
1760
|
+
setText('m-commit', node.localStateCommitHash || '-');
|
|
1761
|
+
setText('m-uptime', 'Uptime: ' + Math.floor(Number(node.uptimeSeconds || 0) / 60) + 'm ' + (Number(node.uptimeSeconds || 0) % 60) + 's');
|
|
1762
|
+
|
|
1763
|
+
// Overview cards
|
|
1764
|
+
setText('ov-tps', Number(pipe.tps60s || 0).toFixed(2) + ' TPS');
|
|
1765
|
+
setText(
|
|
1766
|
+
'ov-tx-totals',
|
|
1767
|
+
'Accepted: ' + String(pipe.txAcceptedTotal ?? 0) +
|
|
1768
|
+
' | Fwd: ' + String(pipe.txForwardedTotal ?? 0) +
|
|
1769
|
+
' | Rejected: ' + String(pipe.txPreFlightRejectedTotal ?? 0)
|
|
1770
|
+
);
|
|
1771
|
+
setText('ov-queue', String((pipe.queueDepth || 0) + (pipe.inFlightPreFlights || 0)) + ' / ' + String(pipe.maxTxRequest || 200));
|
|
1772
|
+
setText('ov-preflight', 'Running: ' + String(pipe.queuePending ?? 0) + ' | Waiting: ' + String(pipe.queueWaiting ?? 0) + ' | PreFlight: ' + String(pipe.inFlightPreFlights ?? 0));
|
|
1773
|
+
setText('ov-sqlite-bytes', formatBytes(storage.totalSqliteBytes));
|
|
1774
|
+
setText('ov-wal-bytes', 'WAL Total: ' + formatBytes(storage.totalWalBytes) + ' | Indexed Txs: ' + String((storage.entityCounts && storage.entityCounts.tx) || 0));
|
|
1775
|
+
setText('ov-mem', 'RSS ' + formatBytes(res.rssBytes) + ' / Heap ' + formatBytes(res.heapUsedBytes));
|
|
1776
|
+
setText(
|
|
1777
|
+
'ov-Lists',
|
|
1778
|
+
'Blocked: ' + String(prefs.blockedAccountCount ?? 0) +
|
|
1779
|
+
' | Trusted: ' + String(prefs.trustedAccountCount ?? 0) +
|
|
1780
|
+
' | Symbols: ' + String(prefs.reservedSymbolCount ?? 0)
|
|
1781
|
+
);
|
|
1782
|
+
|
|
1783
|
+
var viol = lh.violations || {};
|
|
1784
|
+
setText(
|
|
1785
|
+
'ov-ledger-health',
|
|
1786
|
+
(lh.healthy ? 'HEALTHY' : 'VIOLATION') +
|
|
1787
|
+
' — Unfinalized: ' + String(lh.unfinalizedCount ?? 0) +
|
|
1788
|
+
(lh.oldestUnfinalizedAge ? ' (Oldest ' + lh.oldestUnfinalizedAge + ')' : '') +
|
|
1789
|
+
(viol.lag ? ' [LAG!]' : '') +
|
|
1790
|
+
(viol.age ? ' [AGE!]' : '') +
|
|
1791
|
+
(viol.unfinalized ? ' [UNFINALIZED!]' : '')
|
|
1792
|
+
);
|
|
1793
|
+
var th = lh.thresholds || {};
|
|
1794
|
+
setText(
|
|
1795
|
+
'ov-ledger-thresholds',
|
|
1796
|
+
'Thresholds — Lag <= ' + String(th.checkpointLag ?? '-') +
|
|
1797
|
+
', CP Age <= ' + String(th.checkpointAgeMs ?? '-') + 'ms' +
|
|
1798
|
+
', Unfinalized <= ' + String(th.unfinalizedAgeMs ?? '-') + 'ms'
|
|
1799
|
+
);
|
|
1800
|
+
|
|
1801
|
+
setText(
|
|
1802
|
+
'ov-gas-guard',
|
|
1803
|
+
(gas.enabled ? 'ACTIVE' : 'DISABLED') +
|
|
1804
|
+
' — Throttled Actors: ' + String(gas.throttledActors ?? 0) +
|
|
1805
|
+
' | Tracked Actors: ' + String(gas.trackedActors ?? 0)
|
|
1806
|
+
);
|
|
1807
|
+
setText(
|
|
1808
|
+
'ov-gas-guard-sub',
|
|
1809
|
+
'Warning Actors: ' + String(gas.warningActors ?? 0) +
|
|
1810
|
+
' | Slash Triggered: ' + String(gas.slashTriggeredActors ?? 0) +
|
|
1811
|
+
' | Active Bursts: ' + String(gas.activeBurstsInWindow ?? 0) +
|
|
1812
|
+
' | Strike Window: ' + Math.round(Number(gas.strikeWindowMs ?? 0) / 1000) + 's'
|
|
1813
|
+
);
|
|
1814
|
+
|
|
1815
|
+
// Network & Consensus tab
|
|
1816
|
+
var rt = cons.runtime || {};
|
|
1817
|
+
setText('net-view', String(cons.mode || 'single') + (cons.view != null ? ' / View #' + cons.view : '') + (rt.currentLeaderDid ? ' (Leader: ' + rt.currentLeaderDid + ')' : ''));
|
|
1818
|
+
setText(
|
|
1819
|
+
'net-qc',
|
|
1820
|
+
'HighQC: ' + (cons.highQC ? 'v' + cons.highQC.view + ' seq=' + cons.highQC.sequence : '-') +
|
|
1821
|
+
' | LockedQC: ' + (cons.lockedQC ? 'v' + cons.lockedQC.view + ' seq=' + cons.lockedQC.sequence : '-')
|
|
1822
|
+
);
|
|
1823
|
+
setText(
|
|
1824
|
+
'net-witness',
|
|
1825
|
+
'Quorum: ' + String(da.witnessQuorum ?? 0) +
|
|
1826
|
+
' | Circuit: ' + (da.witnessCircuitBroken ? 'BROKEN' : 'OK') +
|
|
1827
|
+
' | Fraud Alerts: ' + String(da.witnessFraudAlertCount ?? 0)
|
|
1828
|
+
);
|
|
1829
|
+
setText('net-proposer', lh.proposer || '-');
|
|
1830
|
+
|
|
1831
|
+
var valTbody = document.getElementById('validators-tbody');
|
|
1832
|
+
clearChildren(valTbody);
|
|
1833
|
+
var vals = Array.isArray(rt.validators) ? rt.validators : [];
|
|
1834
|
+
if (vals.length === 0) {
|
|
1835
|
+
appendRow(valTbody, [lh.proposer || 'single-validator', 'Primary', 'yes', '-', '0', '-']);
|
|
1836
|
+
} else {
|
|
1837
|
+
for (var v = 0; v < vals.length; v++) {
|
|
1838
|
+
var valItem = vals[v];
|
|
1839
|
+
appendRow(valTbody, [
|
|
1840
|
+
(valItem.did || '-') + (valItem.isSelf ? ' (self)' : ''),
|
|
1841
|
+
valItem.isCurrentViewLeader ? 'LEADER' : 'REPLICA',
|
|
1842
|
+
valItem.reachable ? 'yes' : 'no',
|
|
1843
|
+
valItem.lastSeenAt
|
|
1844
|
+
? new Date(valItem.lastSeenAt).toISOString()
|
|
1845
|
+
: valItem.lastSeenAgoMs != null
|
|
1846
|
+
? String(valItem.lastSeenAgoMs) + 'ms ago'
|
|
1847
|
+
: '-',
|
|
1848
|
+
String(valItem.consecutiveSendFailures ?? 0),
|
|
1849
|
+
valItem.consensusUrl || '(redacted)'
|
|
1850
|
+
]);
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
var peersTbody = document.getElementById('peers-tbody');
|
|
1855
|
+
clearChildren(peersTbody);
|
|
1856
|
+
var cands = (rt.leaderRouter && Array.isArray(rt.leaderRouter.candidates)) ? rt.leaderRouter.candidates : [];
|
|
1857
|
+
if (cands.length === 0) {
|
|
1858
|
+
appendRow(peersTbody, ['(none configured)', '-', '-', '-', '-', '-']);
|
|
1859
|
+
} else {
|
|
1860
|
+
for (var c = 0; c < cands.length; c++) {
|
|
1861
|
+
var cand = cands[c];
|
|
1862
|
+
appendRow(peersTbody, [
|
|
1863
|
+
(cand.url || cand.id || '-') + (cand.isActiveLeader ? ' [ACTIVE]' : ''),
|
|
1864
|
+
cand.reachable ? 'yes' : 'no',
|
|
1865
|
+
cand.rttMs != null ? cand.rttMs + ' ms' : '-',
|
|
1866
|
+
cand.latestSequence != null ? String(cand.latestSequence) : '-',
|
|
1867
|
+
cand.checkpointHeight != null ? '#' + cand.checkpointHeight : '-',
|
|
1868
|
+
cand.lastError || '-'
|
|
1869
|
+
]);
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
// Storage & DA tab
|
|
1874
|
+
setText('st-retention', da.retentionMode || '-');
|
|
1875
|
+
setText('st-snapshot', da.snapshotBaseUrl || '(not configured)');
|
|
1876
|
+
setText('st-anchor', da.latestAnchorReceipt ? ('Height #' + da.latestAnchorReceipt.checkpointHeight + ' (' + (da.latestAnchorReceipt.txHash || 'anchored') + ')') : '(none)');
|
|
1877
|
+
setText('st-v2from', lh.entryHashV2From || '-');
|
|
1878
|
+
|
|
1879
|
+
var dbTbody = document.getElementById('db-tbody');
|
|
1880
|
+
clearChildren(dbTbody);
|
|
1881
|
+
var dbs = Array.isArray(storage.databases) ? storage.databases : [];
|
|
1882
|
+
for (var d = 0; d < dbs.length; d++) {
|
|
1883
|
+
var db = dbs[d];
|
|
1884
|
+
appendRow(dbTbody, [
|
|
1885
|
+
db.label,
|
|
1886
|
+
db.filePath || db.fileName,
|
|
1887
|
+
formatBytes(db.mainBytes),
|
|
1888
|
+
formatBytes(db.walBytes),
|
|
1889
|
+
formatBytes(db.shmBytes),
|
|
1890
|
+
formatBytes(db.totalBytes),
|
|
1891
|
+
!db.exists ? 'missing' : db.walWarning ? 'WAL BLOAT WARNING' : 'OK'
|
|
1892
|
+
]);
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
var countsGrid = document.getElementById('entity-counts-grid');
|
|
1896
|
+
clearChildren(countsGrid);
|
|
1897
|
+
var ec = storage.entityCounts || {};
|
|
1898
|
+
var ecKeys = ['tx', 'account', 'asset', 'factory', 'token', 'stake', 'delegation', 'rollup'];
|
|
1899
|
+
for (var k = 0; k < ecKeys.length; k++) {
|
|
1900
|
+
var key = ecKeys[k];
|
|
1901
|
+
var card = document.createElement('div');
|
|
1902
|
+
card.className = 'card';
|
|
1903
|
+
var lbl = document.createElement('div');
|
|
1904
|
+
lbl.className = 'label';
|
|
1905
|
+
lbl.textContent = key;
|
|
1906
|
+
var valEl = document.createElement('div');
|
|
1907
|
+
valEl.className = 'value lg';
|
|
1908
|
+
valEl.textContent = String(ec[key] ?? 0);
|
|
1909
|
+
card.appendChild(lbl);
|
|
1910
|
+
card.appendChild(valEl);
|
|
1911
|
+
countsGrid.appendChild(card);
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
// Operations tab status
|
|
1915
|
+
setText(
|
|
1916
|
+
'ops-sync-meta',
|
|
1917
|
+
'Last SyncNow: ' + (maint.lastSyncNowAt || 'never') +
|
|
1918
|
+
' | Last Filter Flush: ' + (maint.lastReplayFilterPersistAt || 'auto')
|
|
1919
|
+
);
|
|
1920
|
+
setText(
|
|
1921
|
+
'ops-maint-meta',
|
|
1922
|
+
'Pruning: ' + (maint.isPruning ? 'RUNNING' : 'idle') +
|
|
1923
|
+
(maint.lastPruneAt ? ' (last: ' + maint.lastPruneAt + ')' : '') +
|
|
1924
|
+
' | TokenDist: ' + (maint.isUpdatingTokenDistribution ? 'RUNNING' : 'idle')
|
|
1925
|
+
);
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
async function refreshRecentTransactions() {
|
|
1929
|
+
try {
|
|
1930
|
+
var txData = await gql('query { listTransactions(paging: { size: 15 }) { transactions { hash code sender time tx { itx { typeUrl } } } } }');
|
|
1931
|
+
var list = (txData && txData.data && txData.data.listTransactions && txData.data.listTransactions.transactions) || [];
|
|
1932
|
+
var tbody = document.getElementById('tx-tbody');
|
|
1933
|
+
if (!tbody) return;
|
|
1934
|
+
clearChildren(tbody);
|
|
1935
|
+
for (var i = 0; i < list.length; i++) {
|
|
1936
|
+
var item = list[i] || {};
|
|
1937
|
+
var hashSpan = document.createElement('span');
|
|
1938
|
+
hashSpan.className = 'clickable';
|
|
1939
|
+
hashSpan.textContent = item.hash || '-';
|
|
1940
|
+
(function (txHash) {
|
|
1941
|
+
hashSpan.addEventListener('click', function () {
|
|
1942
|
+
var inp = document.getElementById('lookup-input');
|
|
1943
|
+
if (inp && txHash) {
|
|
1944
|
+
inp.value = txHash;
|
|
1945
|
+
inspectValue();
|
|
1946
|
+
}
|
|
1947
|
+
});
|
|
1948
|
+
})(item.hash);
|
|
1949
|
+
appendRow(tbody, [
|
|
1950
|
+
hashSpan,
|
|
1951
|
+
(item.tx && item.tx.itx && item.tx.itx.typeUrl) || '-',
|
|
1952
|
+
item.code || '-',
|
|
1953
|
+
item.sender || '-',
|
|
1954
|
+
item.time || '-'
|
|
1955
|
+
]);
|
|
1956
|
+
}
|
|
1957
|
+
} catch (_e) {}
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
async function inspectValue() {
|
|
1961
|
+
var inputEl = document.getElementById('lookup-input');
|
|
1962
|
+
var outEl = document.getElementById('inspect-output');
|
|
1963
|
+
if (!inputEl || !outEl) return;
|
|
1964
|
+
var q = String(inputEl.value || '').trim();
|
|
1965
|
+
if (!q) {
|
|
1966
|
+
outEl.className = 'hidden';
|
|
1967
|
+
outEl.textContent = '';
|
|
1968
|
+
return;
|
|
1969
|
+
}
|
|
1970
|
+
outEl.className = '';
|
|
1971
|
+
outEl.textContent = 'Querying local verified state...';
|
|
1972
|
+
try {
|
|
1973
|
+
var isHexHash = /^[0-9a-fA-F]{64}$/.test(q);
|
|
1974
|
+
if (isHexHash) {
|
|
1975
|
+
var results = await Promise.all([
|
|
1976
|
+
gql('query($h: String!) { getTx(hash: $h) { code info { hash code sender receiver gasPayer time tx { from nonce itxJson } } } }', { h: q }),
|
|
1977
|
+
fetch(endpoint + '/ledger/proof?hash=' + encodeURIComponent(q), { headers: { Accept: 'application/json' } })
|
|
1978
|
+
.then(function (r) { return r.json(); })
|
|
1979
|
+
.catch(function () { return null; })
|
|
1980
|
+
]);
|
|
1981
|
+
outEl.textContent = JSON.stringify({ transaction: results[0], ledgerProof: results[1] }, null, 2);
|
|
1982
|
+
} else {
|
|
1983
|
+
var payload = await gql(
|
|
1984
|
+
'query($a: String!) { getAccountState(address: $a) { code state { address moniker nonce numTxs numAssets tokens { address symbol value decimal } } } }',
|
|
1985
|
+
{ a: q }
|
|
1986
|
+
);
|
|
1987
|
+
outEl.textContent = JSON.stringify(payload, null, 2);
|
|
1988
|
+
}
|
|
1989
|
+
} catch (err) {
|
|
1990
|
+
outEl.textContent = 'Lookup error: ' + (err && err.message ? err.message : String(err));
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1994
|
+
async function loadAdminConfig() {
|
|
1995
|
+
var hintEl = document.getElementById('cfg-auth-hint');
|
|
1996
|
+
var editorEl = document.getElementById('cfg-editor');
|
|
1997
|
+
try {
|
|
1998
|
+
var res = await fetch(endpoint + '/node/config', { headers: buildHeaders(false) });
|
|
1999
|
+
if (!res.ok) {
|
|
2000
|
+
var errBody = await res.json().catch(function () { return {}; });
|
|
2001
|
+
if (hintEl) {
|
|
2002
|
+
hintEl.classList.remove('hidden');
|
|
2003
|
+
hintEl.textContent = 'Admin authentication required to manage configuration (' + (errBody.error || res.status) + '). Click "Admin Unlock" above.';
|
|
2004
|
+
}
|
|
2005
|
+
if (editorEl) editorEl.classList.add('hidden');
|
|
2006
|
+
return;
|
|
2007
|
+
}
|
|
2008
|
+
var data = await res.json();
|
|
2009
|
+
currentConfigState = data.config;
|
|
2010
|
+
currentCapabilities = data.capabilities || {};
|
|
2011
|
+
if (hintEl) hintEl.classList.add('hidden');
|
|
2012
|
+
if (editorEl) editorEl.classList.remove('hidden');
|
|
2013
|
+
renderConfigEditor(data.config, data.effectiveRuntime || {}, data.capabilities || {});
|
|
2014
|
+
} catch (err) {
|
|
2015
|
+
if (hintEl) {
|
|
2016
|
+
hintEl.classList.remove('hidden');
|
|
2017
|
+
hintEl.textContent = 'Failed to load configuration: ' + (err && err.message ? err.message : String(err));
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
function renderConfigEditor(cfg, eff, caps) {
|
|
2023
|
+
var wpEl = document.getElementById('cfg-write-policy');
|
|
2024
|
+
if (wpEl) wpEl.value = eff.writePolicy || 'reject';
|
|
2025
|
+
var maxEl = document.getElementById('cfg-tx-max');
|
|
2026
|
+
if (maxEl) maxEl.value = String(eff.txMaxRequest || 200);
|
|
2027
|
+
var pollEl = document.getElementById('cfg-poll-ms');
|
|
2028
|
+
if (pollEl) {
|
|
2029
|
+
pollEl.value = eff.pollIntervalMs != null ? String(eff.pollIntervalMs) : '';
|
|
2030
|
+
pollEl.disabled = !caps.canEditFollowerSyncParams;
|
|
2031
|
+
}
|
|
2032
|
+
var lagEl = document.getElementById('cfg-max-lag');
|
|
2033
|
+
if (lagEl) {
|
|
2034
|
+
lagEl.value = eff.maxSyncLag != null ? String(eff.maxSyncLag) : '';
|
|
2035
|
+
lagEl.disabled = !caps.canEditFollowerSyncParams;
|
|
2036
|
+
}
|
|
2037
|
+
var ht = eff.healthThresholds || {};
|
|
2038
|
+
var hlLag = document.getElementById('cfg-hl-lag');
|
|
2039
|
+
if (hlLag) hlLag.value = String(ht.checkpointLag || 1000);
|
|
2040
|
+
var hlAge = document.getElementById('cfg-hl-age');
|
|
2041
|
+
if (hlAge) hlAge.value = String(ht.checkpointAgeMs || 3600000);
|
|
2042
|
+
var hlUnfin = document.getElementById('cfg-hl-unfin');
|
|
2043
|
+
if (hlUnfin) hlUnfin.value = String(ht.unfinalizedAgeMs || 300000);
|
|
2044
|
+
|
|
2045
|
+
var peersWrap = document.getElementById('cfg-peers-wrap');
|
|
2046
|
+
var peersInput = document.getElementById('cfg-peer-urls');
|
|
2047
|
+
if (peersWrap && peersInput) {
|
|
2048
|
+
peersInput.value = Array.isArray(eff.peerUrls) ? eff.peerUrls.join(', ') : '';
|
|
2049
|
+
peersInput.disabled = !caps.canEditFollowerPeers;
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
// Blocked accounts table
|
|
2053
|
+
var bTbody = document.getElementById('cfg-blocked-tbody');
|
|
2054
|
+
clearChildren(bTbody);
|
|
2055
|
+
var blocked = Array.isArray(cfg.blockedAccounts) ? cfg.blockedAccounts : [];
|
|
2056
|
+
for (var i = 0; i < blocked.length; i++) {
|
|
2057
|
+
(function (entry) {
|
|
2058
|
+
var actionNode = '-';
|
|
2059
|
+
if (entry.mutable) {
|
|
2060
|
+
var btn = document.createElement('button');
|
|
2061
|
+
btn.type = 'button';
|
|
2062
|
+
btn.className = 'danger';
|
|
2063
|
+
btn.textContent = 'Remove';
|
|
2064
|
+
btn.addEventListener('click', function () {
|
|
2065
|
+
var remaining = blocked.filter(function (x) { return x.mutable && x.address !== entry.address; });
|
|
2066
|
+
savePreferencesPatch({ blockedAccounts: remaining });
|
|
2067
|
+
});
|
|
2068
|
+
actionNode = btn;
|
|
2069
|
+
}
|
|
2070
|
+
appendRow(bTbody, [entry.address, entry.memo || '-', entry.source + (entry.mutable ? '' : ' (locked)'), actionNode]);
|
|
2071
|
+
})(blocked[i]);
|
|
2072
|
+
}
|
|
2073
|
+
|
|
2074
|
+
// Trusted accounts table
|
|
2075
|
+
var tTbody = document.getElementById('cfg-trusted-tbody');
|
|
2076
|
+
clearChildren(tTbody);
|
|
2077
|
+
var trusted = Array.isArray(cfg.trustedAccounts) ? cfg.trustedAccounts : [];
|
|
2078
|
+
for (var t = 0; t < trusted.length; t++) {
|
|
2079
|
+
(function (entry) {
|
|
2080
|
+
var actionNode = '-';
|
|
2081
|
+
if (entry.mutable) {
|
|
2082
|
+
var btn = document.createElement('button');
|
|
2083
|
+
btn.type = 'button';
|
|
2084
|
+
btn.className = 'danger';
|
|
2085
|
+
btn.textContent = 'Remove';
|
|
2086
|
+
btn.addEventListener('click', function () {
|
|
2087
|
+
var remaining = trusted.filter(function (x) { return x.mutable && x.address !== entry.address; });
|
|
2088
|
+
savePreferencesPatch({ trustedAccounts: remaining });
|
|
2089
|
+
});
|
|
2090
|
+
actionNode = btn;
|
|
2091
|
+
}
|
|
2092
|
+
appendRow(tTbody, [
|
|
2093
|
+
entry.address,
|
|
2094
|
+
entry.tolerance != null ? String(entry.tolerance) : '0',
|
|
2095
|
+
entry.memo || '-',
|
|
2096
|
+
entry.source + (entry.mutable ? '' : ' (locked)'),
|
|
2097
|
+
actionNode
|
|
2098
|
+
]);
|
|
2099
|
+
})(trusted[t]);
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
// Reserved symbols table
|
|
2103
|
+
var symLockMsg = document.getElementById('cfg-symbols-lock-msg');
|
|
2104
|
+
var addSymRow = document.getElementById('add-symbol-row');
|
|
2105
|
+
if (symLockMsg) {
|
|
2106
|
+
symLockMsg.textContent = caps.canEditReservedSymbols
|
|
2107
|
+
? 'Standalone validator: symbol additions persist to preferences.json and apply immediately at pre-queue admission.'
|
|
2108
|
+
: 'Read-only on Follower / Standby / HotStuff cluster nodes to preserve deterministic admission policy.';
|
|
2109
|
+
}
|
|
2110
|
+
if (addSymRow) {
|
|
2111
|
+
if (caps.canEditReservedSymbols) addSymRow.classList.remove('hidden');
|
|
2112
|
+
else addSymRow.classList.add('hidden');
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
var sTbody = document.getElementById('cfg-symbols-tbody');
|
|
2116
|
+
clearChildren(sTbody);
|
|
2117
|
+
var symbols = Array.isArray(cfg.reservedSymbols) ? cfg.reservedSymbols : [];
|
|
2118
|
+
for (var s = 0; s < symbols.length; s++) {
|
|
2119
|
+
(function (entry) {
|
|
2120
|
+
var actionNode = '-';
|
|
2121
|
+
if (entry.mutable && caps.canEditReservedSymbols) {
|
|
2122
|
+
var btn = document.createElement('button');
|
|
2123
|
+
btn.type = 'button';
|
|
2124
|
+
btn.className = 'danger';
|
|
2125
|
+
btn.textContent = 'Remove';
|
|
2126
|
+
btn.addEventListener('click', function () {
|
|
2127
|
+
var remaining = symbols.filter(function (x) { return x.mutable && x.symbol !== entry.symbol; });
|
|
2128
|
+
savePreferencesPatch({ reservedSymbols: remaining });
|
|
2129
|
+
});
|
|
2130
|
+
actionNode = btn;
|
|
2131
|
+
}
|
|
2132
|
+
appendRow(sTbody, [entry.symbol, entry.memo || '-', entry.source + (entry.mutable ? '' : ' (locked)'), actionNode]);
|
|
2133
|
+
})(symbols[s]);
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
async function savePreferencesPatch(patch) {
|
|
2138
|
+
try {
|
|
2139
|
+
var res = await fetch(endpoint + '/node/config', {
|
|
2140
|
+
method: 'PUT',
|
|
2141
|
+
headers: buildHeaders(true),
|
|
2142
|
+
body: JSON.stringify(patch)
|
|
2143
|
+
});
|
|
2144
|
+
var data = await res.json().catch(function () { return {}; });
|
|
2145
|
+
if (!res.ok) {
|
|
2146
|
+
showNotice('Config update rejected: ' + (data.error || res.status), 'err');
|
|
2147
|
+
return;
|
|
2148
|
+
}
|
|
2149
|
+
showNotice(
|
|
2150
|
+
'Configuration saved & hot-applied' + (data.requiresRestart ? ' (restart required for reservedSymbols).' : '.'),
|
|
2151
|
+
'ok'
|
|
2152
|
+
);
|
|
2153
|
+
await loadAdminConfig();
|
|
2154
|
+
await refreshDashboard();
|
|
2155
|
+
} catch (err) {
|
|
2156
|
+
showNotice('Config update failed: ' + (err && err.message ? err.message : String(err)), 'err');
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
async function invokeMaintenanceAction(pathSuffix, bodyObj) {
|
|
2161
|
+
var outEl = document.getElementById('ops-output');
|
|
2162
|
+
try {
|
|
2163
|
+
var res = await fetch(endpoint + '/node/actions/' + pathSuffix, {
|
|
2164
|
+
method: 'POST',
|
|
2165
|
+
headers: buildHeaders(true),
|
|
2166
|
+
body: JSON.stringify(bodyObj || {})
|
|
2167
|
+
});
|
|
2168
|
+
var data = await res.json().catch(function () { return {}; });
|
|
2169
|
+
if (outEl) {
|
|
2170
|
+
outEl.className = '';
|
|
2171
|
+
outEl.textContent = JSON.stringify(data, null, 2);
|
|
2172
|
+
}
|
|
2173
|
+
if (!res.ok) {
|
|
2174
|
+
showNotice('Action failed: ' + (data.error || res.status), 'err');
|
|
2175
|
+
} else {
|
|
2176
|
+
showNotice('Action "' + pathSuffix + '" completed.', 'ok');
|
|
2177
|
+
await refreshDashboard();
|
|
2178
|
+
}
|
|
2179
|
+
} catch (err) {
|
|
2180
|
+
showNotice('Action error: ' + (err && err.message ? err.message : String(err)), 'err');
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
async function downloadDiagnostics() {
|
|
2185
|
+
try {
|
|
2186
|
+
var res = await fetch(endpoint + '/node/diagnostics', { headers: buildHeaders(false) });
|
|
2187
|
+
if (!res.ok) {
|
|
2188
|
+
var errBody = await res.json().catch(function () { return {}; });
|
|
2189
|
+
showNotice('Diagnostics download failed: ' + (errBody.error || res.status), 'err');
|
|
2190
|
+
return;
|
|
2191
|
+
}
|
|
2192
|
+
var text = await res.text();
|
|
2193
|
+
var blob = new Blob([text], { type: 'application/json' });
|
|
2194
|
+
var url = URL.createObjectURL(blob);
|
|
2195
|
+
var a = document.createElement('a');
|
|
2196
|
+
a.href = url;
|
|
2197
|
+
a.download = 'chain-diagnostics-' + Date.now() + '.json';
|
|
2198
|
+
document.body.appendChild(a);
|
|
2199
|
+
a.click();
|
|
2200
|
+
document.body.removeChild(a);
|
|
2201
|
+
URL.revokeObjectURL(url);
|
|
2202
|
+
showNotice('Diagnostics JSON downloaded.', 'ok');
|
|
2203
|
+
} catch (err) {
|
|
2204
|
+
showNotice('Diagnostics error: ' + (err && err.message ? err.message : String(err)), 'err');
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
|
|
2208
|
+
function wireEvents() {
|
|
2209
|
+
var tabBtns = document.querySelectorAll('.tab-btn');
|
|
2210
|
+
for (var i = 0; i < tabBtns.length; i++) {
|
|
2211
|
+
(function (btn) {
|
|
2212
|
+
btn.addEventListener('click', function () {
|
|
2213
|
+
switchTab(btn.getAttribute('data-tab') || 'overview');
|
|
2214
|
+
if (activeTab === 'explorer') refreshRecentTransactions();
|
|
2215
|
+
});
|
|
2216
|
+
})(tabBtns[i]);
|
|
2217
|
+
}
|
|
2218
|
+
|
|
2219
|
+
var lookupBtn = document.getElementById('lookup-btn');
|
|
2220
|
+
if (lookupBtn) lookupBtn.addEventListener('click', inspectValue);
|
|
2221
|
+
|
|
2222
|
+
var refreshBtn = document.getElementById('refresh-btn');
|
|
2223
|
+
if (refreshBtn) refreshBtn.addEventListener('click', refreshDashboard);
|
|
2224
|
+
|
|
2225
|
+
var autoBtn = document.getElementById('auto-refresh-btn');
|
|
2226
|
+
if (autoBtn) {
|
|
2227
|
+
autoBtn.addEventListener('click', function () {
|
|
2228
|
+
autoRefreshEnabled = !autoRefreshEnabled;
|
|
2229
|
+
autoBtn.textContent = autoRefreshEnabled ? 'Auto: 5s' : 'Auto: Off';
|
|
2230
|
+
});
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
var authToggle = document.getElementById('auth-toggle-btn');
|
|
2234
|
+
var authBar = document.getElementById('auth-bar');
|
|
2235
|
+
if (authToggle && authBar) {
|
|
2236
|
+
authToggle.addEventListener('click', function () {
|
|
2237
|
+
authBar.classList.toggle('hidden');
|
|
2238
|
+
});
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
var adminSave = document.getElementById('admin-save-btn');
|
|
2242
|
+
if (adminSave) {
|
|
2243
|
+
adminSave.addEventListener('click', function () {
|
|
2244
|
+
var inp = document.getElementById('admin-token-input');
|
|
2245
|
+
var val = inp ? String(inp.value || '').trim() : '';
|
|
2246
|
+
setAdminToken(val);
|
|
2247
|
+
if (inp) inp.value = '';
|
|
2248
|
+
if (authBar) authBar.classList.add('hidden');
|
|
2249
|
+
showNotice(val ? 'Admin token stored in sessionStorage.' : 'Admin token cleared.', 'ok');
|
|
2250
|
+
refreshDashboard();
|
|
2251
|
+
if (activeTab === 'config') loadAdminConfig();
|
|
2252
|
+
});
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2255
|
+
var adminClear = document.getElementById('admin-clear-btn');
|
|
2256
|
+
if (adminClear) {
|
|
2257
|
+
adminClear.addEventListener('click', function () {
|
|
2258
|
+
setAdminToken('');
|
|
2259
|
+
showNotice('Admin session locked.', 'ok');
|
|
2260
|
+
refreshDashboard();
|
|
2261
|
+
if (activeTab === 'config') loadAdminConfig();
|
|
2262
|
+
});
|
|
2263
|
+
}
|
|
2264
|
+
|
|
2265
|
+
var saveRtBtn = document.getElementById('cfg-save-runtime-btn');
|
|
2266
|
+
if (saveRtBtn) {
|
|
2267
|
+
saveRtBtn.addEventListener('click', function () {
|
|
2268
|
+
var rt = {
|
|
2269
|
+
writePolicy: document.getElementById('cfg-write-policy').value,
|
|
2270
|
+
txMaxRequest: Number(document.getElementById('cfg-tx-max').value || 200),
|
|
2271
|
+
healthThresholds: {
|
|
2272
|
+
checkpointLag: Number(document.getElementById('cfg-hl-lag').value || 1000),
|
|
2273
|
+
checkpointAgeMs: Number(document.getElementById('cfg-hl-age').value || 3600000),
|
|
2274
|
+
unfinalizedAgeMs: Number(document.getElementById('cfg-hl-unfin').value || 300000)
|
|
2275
|
+
}
|
|
2276
|
+
};
|
|
2277
|
+
if (currentCapabilities && currentCapabilities.canEditFollowerSyncParams) {
|
|
2278
|
+
var pVal = document.getElementById('cfg-poll-ms').value;
|
|
2279
|
+
var lVal = document.getElementById('cfg-max-lag').value;
|
|
2280
|
+
if (pVal) rt.pollIntervalMs = Number(pVal);
|
|
2281
|
+
if (lVal !== '') rt.maxSyncLag = Number(lVal);
|
|
2282
|
+
}
|
|
2283
|
+
if (currentCapabilities && currentCapabilities.canEditFollowerPeers) {
|
|
2284
|
+
var rawPeers = String(document.getElementById('cfg-peer-urls').value || '');
|
|
2285
|
+
rt.peerUrls = rawPeers.split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
|
2286
|
+
}
|
|
2287
|
+
savePreferencesPatch({ runtime: rt });
|
|
2288
|
+
});
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
var addBlockedBtn = document.getElementById('add-blocked-btn');
|
|
2292
|
+
if (addBlockedBtn) {
|
|
2293
|
+
addBlockedBtn.addEventListener('click', function () {
|
|
2294
|
+
var addr = String(document.getElementById('add-blocked-addr').value || '').trim();
|
|
2295
|
+
var memo = String(document.getElementById('add-blocked-memo').value || '').trim();
|
|
2296
|
+
if (!addr || !currentConfigState) return;
|
|
2297
|
+
var list = (currentConfigState.blockedAccounts || [])
|
|
2298
|
+
.filter(function (x) { return x.mutable; })
|
|
2299
|
+
.map(function (x) { return x.memo ? { address: x.address, memo: x.memo } : { address: x.address }; });
|
|
2300
|
+
list.push(memo ? { address: addr, memo: memo } : { address: addr });
|
|
2301
|
+
document.getElementById('add-blocked-addr').value = '';
|
|
2302
|
+
document.getElementById('add-blocked-memo').value = '';
|
|
2303
|
+
savePreferencesPatch({ blockedAccounts: list });
|
|
2304
|
+
});
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
var addTrustedBtn = document.getElementById('add-trusted-btn');
|
|
2308
|
+
if (addTrustedBtn) {
|
|
2309
|
+
addTrustedBtn.addEventListener('click', function () {
|
|
2310
|
+
var addr = String(document.getElementById('add-trusted-addr').value || '').trim();
|
|
2311
|
+
var tolRaw = String(document.getElementById('add-trusted-tol').value || '').trim();
|
|
2312
|
+
var memo = String(document.getElementById('add-trusted-memo').value || '').trim();
|
|
2313
|
+
if (!addr || !currentConfigState) return;
|
|
2314
|
+
var list = (currentConfigState.trustedAccounts || [])
|
|
2315
|
+
.filter(function (x) { return x.mutable; })
|
|
2316
|
+
.map(function (x) {
|
|
2317
|
+
var item = { address: x.address };
|
|
2318
|
+
if (x.tolerance != null) item.tolerance = x.tolerance;
|
|
2319
|
+
if (x.memo) item.memo = x.memo;
|
|
2320
|
+
return item;
|
|
2321
|
+
});
|
|
2322
|
+
var nextItem = { address: addr };
|
|
2323
|
+
if (tolRaw !== '') nextItem.tolerance = Number(tolRaw);
|
|
2324
|
+
if (memo) nextItem.memo = memo;
|
|
2325
|
+
list.push(nextItem);
|
|
2326
|
+
document.getElementById('add-trusted-addr').value = '';
|
|
2327
|
+
document.getElementById('add-trusted-tol').value = '';
|
|
2328
|
+
document.getElementById('add-trusted-memo').value = '';
|
|
2329
|
+
savePreferencesPatch({ trustedAccounts: list });
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
|
|
2333
|
+
var addSymBtn = document.getElementById('add-symbol-btn');
|
|
2334
|
+
if (addSymBtn) {
|
|
2335
|
+
addSymBtn.addEventListener('click', function () {
|
|
2336
|
+
var sym = String(document.getElementById('add-symbol-val').value || '').trim().toUpperCase();
|
|
2337
|
+
var memo = String(document.getElementById('add-symbol-memo').value || '').trim();
|
|
2338
|
+
if (!sym || !currentConfigState) return;
|
|
2339
|
+
var list = (currentConfigState.reservedSymbols || [])
|
|
2340
|
+
.filter(function (x) { return x.mutable; })
|
|
2341
|
+
.map(function (x) { return x.memo ? { symbol: x.symbol, memo: x.memo } : { symbol: x.symbol }; });
|
|
2342
|
+
list.push(memo ? { symbol: sym, memo: memo } : { symbol: sym });
|
|
2343
|
+
document.getElementById('add-symbol-val').value = '';
|
|
2344
|
+
document.getElementById('add-symbol-memo').value = '';
|
|
2345
|
+
savePreferencesPatch({ reservedSymbols: list });
|
|
2346
|
+
});
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
var syncBtn = document.getElementById('act-sync-btn');
|
|
2350
|
+
if (syncBtn) syncBtn.addEventListener('click', function () { invokeMaintenanceAction('sync-now', {}); });
|
|
2351
|
+
var reloadBtn = document.getElementById('act-reload-prefs-btn');
|
|
2352
|
+
if (reloadBtn) reloadBtn.addEventListener('click', function () { invokeMaintenanceAction('reload-preferences', {}); });
|
|
2353
|
+
var flushBtn = document.getElementById('act-persist-filter-btn');
|
|
2354
|
+
if (flushBtn) flushBtn.addEventListener('click', function () { invokeMaintenanceAction('persist-replay-filter', {}); });
|
|
2355
|
+
var pruneDryBtn = document.getElementById('act-prune-dry-btn');
|
|
2356
|
+
if (pruneDryBtn) pruneDryBtn.addEventListener('click', function () { invokeMaintenanceAction('indexdb-prune', { findOnly: true }); });
|
|
2357
|
+
var pruneRunBtn = document.getElementById('act-prune-run-btn');
|
|
2358
|
+
if (pruneRunBtn) pruneRunBtn.addEventListener('click', function () { invokeMaintenanceAction('indexdb-prune', { findOnly: false }); });
|
|
2359
|
+
var distBtn = document.getElementById('act-dist-btn');
|
|
2360
|
+
if (distBtn) {
|
|
2361
|
+
distBtn.addEventListener('click', function () {
|
|
2362
|
+
var tokAddr = String(document.getElementById('act-dist-token').value || '').trim();
|
|
2363
|
+
invokeMaintenanceAction('update-token-distribution', { force: true, tokenAddress: tokAddr || undefined });
|
|
2364
|
+
});
|
|
2365
|
+
}
|
|
2366
|
+
var diagBtn = document.getElementById('act-diag-btn');
|
|
2367
|
+
if (diagBtn) diagBtn.addEventListener('click', downloadDiagnostics);
|
|
2368
|
+
}
|
|
2369
|
+
|
|
2370
|
+
updateAuthUi();
|
|
2371
|
+
wireEvents();
|
|
2372
|
+
switchTab(activeTab);
|
|
2373
|
+
refreshDashboard();
|
|
2374
|
+
refreshRecentTransactions();
|
|
2375
|
+
|
|
2376
|
+
autoRefreshTimer = setInterval(function () {
|
|
2377
|
+
if (autoRefreshEnabled && !document.hidden) {
|
|
2378
|
+
refreshDashboard();
|
|
2379
|
+
}
|
|
2380
|
+
}, 5000);
|
|
2381
|
+
})();
|
|
2382
|
+
`;
|
|
2383
|
+
function applyStrictConsoleHeaders(res) {
|
|
2384
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
2385
|
+
res.setHeader("X-Frame-Options", "DENY");
|
|
2386
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
2387
|
+
res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'");
|
|
2388
|
+
}
|
|
2389
|
+
function safeJsonLiteral(value) {
|
|
2390
|
+
return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
2391
|
+
}
|
|
2392
|
+
/**
|
|
2393
|
+
* Express middleware serving the Unified Chain Console at a configurable `mountPath`
|
|
2394
|
+
* (e.g., `/dashboard` on standalone chain nodes or `/` inside `@ocap/chain-dashboard` Blocklet).
|
|
2395
|
+
*/
|
|
2396
|
+
function createUnifiedConsoleMiddleware(options = {}) {
|
|
2397
|
+
const rawMount = (options.mountPath || "/dashboard").trim() || "/dashboard";
|
|
2398
|
+
const mountPath = rawMount === "/" ? "/" : `/${rawMount.replace(/^\/+|\/+$/g, "")}`;
|
|
2399
|
+
const chainEndpoint = (options.chainEndpoint || "/api").trim() || "/api";
|
|
2400
|
+
const html = buildUnifiedConsoleHtml({
|
|
2401
|
+
appBasePath: mountPath,
|
|
2402
|
+
defaultTab: options.defaultTab || "overview"
|
|
2403
|
+
});
|
|
2404
|
+
return (req, res, next) => {
|
|
2405
|
+
const reqPath = req.path || "/";
|
|
2406
|
+
if (reqPath === "/consensus" || reqPath.startsWith("/consensus/")) return res.status(404).json({ error: "Not found" });
|
|
2407
|
+
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
2408
|
+
if (reqPath === "/__blocklet__.js") {
|
|
2409
|
+
const cfg = options.getConfig?.() ?? {};
|
|
2410
|
+
const chainId = String(cfg.chainId || "local-chain");
|
|
2411
|
+
const payload = {
|
|
2412
|
+
appId: chainId,
|
|
2413
|
+
appName: chainId,
|
|
2414
|
+
prefix: mountPath,
|
|
2415
|
+
mountPoints: [{
|
|
2416
|
+
name: "chain-api",
|
|
2417
|
+
mountPoint: chainEndpoint
|
|
2418
|
+
}, {
|
|
2419
|
+
name: "chain-dashboard",
|
|
2420
|
+
mountPoint: mountPath
|
|
2421
|
+
}],
|
|
2422
|
+
env: {
|
|
2423
|
+
CHAIN_API_ENDPOINT: chainEndpoint,
|
|
2424
|
+
EXPLORER_CHAIN_ENDPOINT: chainEndpoint
|
|
2425
|
+
}
|
|
2426
|
+
};
|
|
2427
|
+
applyStrictConsoleHeaders(res);
|
|
2428
|
+
res.setHeader("Content-Type", "application/javascript; charset=utf-8");
|
|
2429
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
2430
|
+
return res.status(200).send(`window.blocklet = ${safeJsonLiteral(payload)};\n`);
|
|
2431
|
+
}
|
|
2432
|
+
if (reqPath === "/static/js/networks.js") {
|
|
2433
|
+
const cfg = options.getConfig?.() ?? {};
|
|
2434
|
+
const chainId = String(cfg.chainId || "local-chain");
|
|
2435
|
+
const networks = [{
|
|
2436
|
+
id: chainId,
|
|
2437
|
+
name: chainId,
|
|
2438
|
+
abbr: cfg.token?.symbol || "ARC",
|
|
2439
|
+
endpoint: chainEndpoint,
|
|
2440
|
+
localFollower: true
|
|
2441
|
+
}];
|
|
2442
|
+
applyStrictConsoleHeaders(res);
|
|
2443
|
+
res.setHeader("Content-Type", "application/javascript; charset=utf-8");
|
|
2444
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
2445
|
+
return res.status(200).send(`window.networks = ${safeJsonLiteral(networks)};\n`);
|
|
2446
|
+
}
|
|
2447
|
+
let subPath = null;
|
|
2448
|
+
if (mountPath === "/") {
|
|
2449
|
+
if (reqPath === "/api" || reqPath.startsWith("/api/") || reqPath === "/node" || reqPath.startsWith("/node/") || reqPath === "/blocked") return next();
|
|
2450
|
+
subPath = reqPath;
|
|
2451
|
+
} else if (reqPath === mountPath || reqPath.startsWith(`${mountPath}/`)) subPath = reqPath.slice(mountPath.length) || "/";
|
|
2452
|
+
else return next();
|
|
2453
|
+
let decodedSubPath;
|
|
2454
|
+
try {
|
|
2455
|
+
decodedSubPath = decodeURIComponent(subPath);
|
|
2456
|
+
} catch {
|
|
2457
|
+
applyStrictConsoleHeaders(res);
|
|
2458
|
+
return res.status(400).type("text/plain").send("Invalid URI path");
|
|
2459
|
+
}
|
|
2460
|
+
if (decodedSubPath.includes("\0") || decodedSubPath.includes("\\") || decodedSubPath.split("/").includes("..")) {
|
|
2461
|
+
applyStrictConsoleHeaders(res);
|
|
2462
|
+
return res.status(400).type("text/plain").send("Forbidden path segment");
|
|
2463
|
+
}
|
|
2464
|
+
if (decodedSubPath === "/app.js") {
|
|
2465
|
+
applyStrictConsoleHeaders(res);
|
|
2466
|
+
res.setHeader("Content-Type", "application/javascript; charset=utf-8");
|
|
2467
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
2468
|
+
return res.status(200).send(UNIFIED_CONSOLE_APP_JS);
|
|
2469
|
+
}
|
|
2470
|
+
if (decodedSubPath === "/" || decodedSubPath === "/index.html") {
|
|
2471
|
+
applyStrictConsoleHeaders(res);
|
|
2472
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
2473
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
2474
|
+
return res.status(200).send(html);
|
|
2475
|
+
}
|
|
2476
|
+
return next();
|
|
2477
|
+
};
|
|
2478
|
+
}
|
|
2479
|
+
|
|
2480
|
+
//#endregion
|
|
2481
|
+
export { UNIFIED_CONSOLE_APP_JS, buildUnifiedConsoleHtml, collectLedgerHealthSummary, createNodeDashboardRouter, createNodeMaintenanceController, createUnifiedConsoleMiddleware, isDashboardEnabled };
|