-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
3865 lines (3535 loc) · 160 KB
/
server.js
File metadata and controls
3865 lines (3535 loc) · 160 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ─── Plan Manager Server ──────────────────────────────────────────────────────
// Express backend for Sentinel dVPN plan management.
// Modules: lib/constants, lib/errors, lib/protobuf, lib/chain, lib/wallet
// Cache (cached/cacheInvalidate/cacheClear) imported from blue-js-sdk.
import 'dotenv/config';
import express from 'express';
import QRCode from 'qrcode';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { readFileSync, writeFileSync, existsSync, mkdirSync, statSync } from 'fs';
import {
listNodes,
fetchAllNodes as sdkFetchAllChainNodes,
enrichNodes as sdkEnrichNodes,
nodeStatusV3,
registerCleanupHandlers,
disconnect,
cached,
cacheInvalidate,
cacheClear,
buildFeeGrantMsg,
buildRevokeFeeGrantMsg,
} from 'blue-js-sdk';
// ─── Module Imports ──────────────────────────────────────────────────────────
import { PORT, LCD_ENDPOINTS, RPC_PROVIDERS, RPC_ENDPOINTS, NODE_CACHE_TTL } from './lib/constants.js';
import * as C from './lib/constants.js';
// Chain error parsing + plan-specific helpers (kept local — SDK's parseChainError lacks plan/lease patterns)
import { parseChainError, isLeaseNotFound, isDuplicateNode, txResponse } from './lib/errors.js';
import {
lcd,
getDvpnPrice,
getSigningClient,
resetSigningClient,
safeBroadcast,
getRpcClient,
rpcQueryNode,
rpcQueryNodes,
rpcQueryNodesForPlan,
rpcQuerySessionsForAccount,
rpcQuerySubscriptionsForPlan,
rpcQueryFeeGrants,
rpcQueryFeeGrantsIssued,
rpcQueryPlan,
rpcQueryProvider,
rpcQueryBalance,
KeplrSignRequiredError,
broadcastSignedTx,
} from './lib/chain.js';
import { getAddr, getProvAddr, requireWallet } from './lib/wallet.js';
import {
initSession, isMultiUser, encryptMnemonic, decryptMnemonic,
sessionFromMnemonic, runWithSession, currentSession, parseCookies,
buildSetCookie, buildClearCookie, COOKIE_NAME, dropSessionFromCache,
KEPLR_COOKIE_NAME, keplrSessionFromAddress, dropKeplrSessionFromCache,
buildKeplrToken, parseKeplrToken, buildSetKeplrCookie, buildClearKeplrCookie,
} from './lib/session.js';
registerCleanupHandlers();
const __dirname = dirname(fileURLToPath(import.meta.url));
// DATA_DIR lets deployments (Docker, etc.) redirect state files to a mounted
// volume. Defaults to the project root — unchanged for local installs.
const DATA_DIR = process.env.DATA_DIR || __dirname;
try { mkdirSync(DATA_DIR, { recursive: true }); } catch {}
initSession(DATA_DIR);
// ─── Demo Mode ────────────────────────────────────────────────────────────────
// Read-only browse: any visitor sees the UI mounted on a watch-only address
// without supplying a mnemonic. Every TX-broadcasting endpoint returns 403.
// Set DEMO_ADDR to any sent1... operator address you want visitors to view.
// Curated default operator: owns mainnet plans 36 & 41 (47 active subs, 731
// linked nodes at time of writing). Override with env DEMO_ADDR for any other
// sent1... address. Picked so `DEMO=true npm start` works zero-config and
// shows a populated dashboard, not an empty operator with nothing to render.
const DEFAULT_DEMO_ADDR = 'sent1t0xjyflrah5n36rfkpfeuw6pz6vl2g27x2793l';
const DEMO_MODE = String(process.env.DEMO || '').toLowerCase() === 'true';
const DEMO_ADDR = (process.env.DEMO_ADDR || '').trim() || (DEMO_MODE ? DEFAULT_DEMO_ADDR : '');
if (DEMO_MODE) {
if (!DEMO_ADDR || !DEMO_ADDR.startsWith('sent1')) {
console.error('[demo] DEMO=true requires DEMO_ADDR=sent1... (operator address to display).');
process.exit(1);
}
// Validate bech32 checksum so a typo fails fast at boot instead of crashing
// on first request (keplrSessionFromAddress throws on invalid checksum).
try {
const { fromBech32 } = await import('@cosmjs/encoding');
const { prefix } = fromBech32(DEMO_ADDR);
if (prefix !== 'sent') throw new Error(`expected sent prefix, got ${prefix}`);
} catch (err) {
console.error(`[demo] DEMO_ADDR is not a valid sentinel address: ${err.message}`);
process.exit(1);
}
console.log(`[demo] Read-only mode enabled — mounted on ${DEMO_ADDR}. Writes return 403.`);
}
// ─── Boot Pre-flight ──────────────────────────────────────────────────────────
// Warn about partial Privy config at boot — the email login card mounts but
// /api/wallet/privy-login returns 503, leaving users stuck staring at "send
// code did nothing" with no clue why. Catch it here, in the startup log,
// where ops actually look.
{
const privyVars = [
['PRIVY_APP_ID', process.env.PRIVY_APP_ID],
['PRIVY_APP_SECRET', process.env.PRIVY_APP_SECRET],
['PRIVY_CLIENT_ID', process.env.PRIVY_CLIENT_ID],
];
const set = privyVars.filter(([, v]) => v && v.trim());
if (set.length > 0 && set.length < 3) {
const missing = privyVars.filter(([, v]) => !v || !v.trim()).map(([k]) => k).join(', ');
console.warn(`[privy] Partial config: ${set.length}/3 vars set. Missing: ${missing}. Email login will fail until all three are set or all three are empty.`);
}
}
const app = express();
app.use(express.json({ limit: '32kb' }));
// Suppress fingerprinting header.
app.disable('x-powered-by');
// Trust the loopback proxy so req.secure reflects the X-Forwarded-Proto
// header when an HTTPS-terminating reverse proxy fronts us on localhost.
app.set('trust proxy', 'loopback');
// ─── Security Headers (FIX 4) ─────────────────────────────────────────────────
// TODO: Move to nonce-based CSP to eliminate 'unsafe-inline' for script-src.
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy',
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline'; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data:; " +
"connect-src 'self' https://lcd.sentinel.co https://api.sentinel.quokkastake.io https://sentinel-api.polkachu.com https://sentinel.api.trivium.network:1317 https://auth.privy.io https://*.privy.io https://*.rpc.privy.systems; " +
"object-src 'none'; " +
"base-uri 'self'; " +
"frame-ancestors 'none'"
);
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
next();
});
// ─── CSRF Protection (FIX 3) ─────────────────────────────────────────────────
// Non-GET requests must be same-origin OR carry an allow-listed Origin OR
// include X-Requested-With (impossible to set on a classic cross-site form).
//
// Same-origin is derived from the Host header so the server keeps working
// regardless of the deploy URL (http://localhost:8000, https://my.domain, a
// reverse proxy, etc.) without needing reconfiguration. For cross-origin
// callers (embeds, third-party dashboards) set ALLOWED_ORIGINS as a
// comma-separated list.
const EXTRA_ALLOWED_ORIGINS = (process.env.ALLOWED_ORIGINS || '')
.split(',').map(s => s.trim()).filter(Boolean);
function isSameOrigin(req) {
const origin = req.headers['origin'];
const host = req.headers['host'];
if (!origin || !host) return false;
try { return new URL(origin).host === host; } catch { return false; }
}
app.use((req, res, next) => {
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
const origin = req.headers['origin'];
const xrw = req.headers['x-requested-with'];
if (isSameOrigin(req)) return next();
if (origin && EXTRA_ALLOWED_ORIGINS.includes(origin)) return next();
if (!origin && xrw === 'XMLHttpRequest') return next();
return res.status(403).json({ error: 'CSRF blocked' });
});
// ─── Static Files (FIX 1) — serves only public/ ──────────────────────────────
app.use(express.static(join(__dirname, 'public'), {
setHeaders(res, path) {
// Browsers refuse to evaluate .mjs files unless the MIME type says JS.
if (path.endsWith('.mjs')) res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
},
}));
// ─── Per-Request Session Middleware ───────────────────────────────────────
// Decrypts the httpOnly session cookie (if present) into a wallet and runs
// the rest of the request chain inside that session's AsyncLocalStorage
// context. Handlers call `getAddr()` / `getSigningClient()` as before;
// those helpers automatically resolve to the per-request wallet.
//
// In DEMO_MODE, every request without a real auth cookie is mounted on the
// configured DEMO_ADDR as a watch-only session (kind: 'demo'). The write
// gate below rejects POST/PUT/DELETE before any TX can be broadcast.
app.use(async (req, res, next) => {
const cookies = parseCookies(req.headers.cookie);
const mnemonicToken = cookies[COOKIE_NAME];
const keplrToken = cookies[KEPLR_COOKIE_NAME];
if (DEMO_MODE && !mnemonicToken && !keplrToken) {
const session = keplrSessionFromAddress(DEMO_ADDR, null, 'demo');
return runWithSession(session, () => next());
}
if (mnemonicToken) {
try {
const mnemonic = decryptMnemonic(mnemonicToken);
const session = await sessionFromMnemonic(mnemonic);
return runWithSession(session, () => next());
} catch (err) {
// Cookie decrypt + wallet derivation are pure crypto — no broadcast,
// no KEPLR_SIGN_REQUIRED can surface here. Just clear the bad cookie.
console.warn('[session] Rejecting mnemonic cookie:', err.message);
res.setHeader('Set-Cookie', buildClearCookie({ secure: req.secure }));
// Fall through to Keplr probe (mnemonic and Keplr can't both be active,
// but a stale mnemonic cookie shouldn't lock out an otherwise-valid
// Keplr session).
}
}
if (keplrToken) {
const parsed = parseKeplrToken(keplrToken);
if (parsed) {
// Same cookie shape is reused for Privy logins (server-custody cosmos
// wallet); look the address up in privy-wallets.json to mark the
// session kind correctly so the UI can show "Privy (email)" instead of
// "Keplr extension" and so the right signing path is taken later.
const kind = lookupPrivyWalletByAddr(parsed.addr) ? 'privy' : 'keplr';
const session = keplrSessionFromAddress(parsed.addr, parsed.pubkeyB64, kind);
return runWithSession(session, () => next());
}
console.warn('[session] Rejecting Keplr cookie (HMAC mismatch)');
res.setHeader('Set-Cookie', buildClearKeplrCookie({ secure: req.secure }));
}
next();
});
// ─── Demo Write Gate ──────────────────────────────────────────────────────────
// Demo sessions can read but not write. Reject any state-changing method
// (POST/PUT/DELETE/PATCH) with a clear 403 so the UI can surface a banner.
app.use((req, res, next) => {
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
if (currentSession()?.kind !== 'demo') return next();
return res.status(403).json({ error: 'Demo mode is read-only — clone the repo and set MNEMONIC to make transactions.', demo: true });
});
// ─── Plan ID Persistence ──────────────────────────────────────────────────────
// Keyed by wallet address so multi-user deploys keep each operator's plan
// list separate. Legacy flat-array files (single-user installs) are migrated
// to the per-address map on first read.
const MY_PLANS_FILE = join(DATA_DIR, 'my-plans.json');
function readPlanStore() {
try {
if (!existsSync(MY_PLANS_FILE)) return {};
const parsed = JSON.parse(readFileSync(MY_PLANS_FILE, 'utf8'));
// Legacy shape: flat array. Stash it under the currently-loaded wallet
// so nothing is lost; if there's no wallet yet, park it under '_legacy'
// and the first wallet to load gets a merge.
if (Array.isArray(parsed)) {
const owner = getAddr() || '_legacy';
return { [owner]: parsed.map(Number) };
}
return parsed && typeof parsed === 'object' ? parsed : {};
} catch (err) {
// Helper has no `res` in scope — log and return safe default.
console.error('Failed to load my-plans.json:', err.message);
return {};
}
}
function loadMyPlanIds() {
const store = readPlanStore();
const addr = getAddr();
if (!addr) return [];
const list = store[addr] || [];
// Opportunistically absorb any legacy-bucket plans the first time this
// wallet loads them.
if (store._legacy && store[addr] !== store._legacy) {
const merged = Array.from(new Set([...list, ...store._legacy]));
store[addr] = merged;
delete store._legacy;
try { writeFileSync(MY_PLANS_FILE, JSON.stringify(store), 'utf8'); } catch {}
return merged;
}
return list;
}
function saveMyPlanId(id) {
const addr = getAddr();
if (!addr) return;
const store = readPlanStore();
const list = store[addr] || [];
if (!list.includes(Number(id))) {
list.push(Number(id));
store[addr] = list;
writeFileSync(MY_PLANS_FILE, JSON.stringify(store), 'utf8');
}
}
/**
* Drop plan IDs from the per-wallet `my-plans.json` ledger. Used to evict
* stale entries left over from a different mnemonic — these would otherwise
* surface in the UI and produce "address … is not authorized" errors when
* the user tries to link nodes / change status / etc.
*/
function dropMyPlanIds(ids) {
const addr = getAddr();
if (!addr || !ids || ids.length === 0) return;
const drop = new Set(ids.map(Number));
const store = readPlanStore();
const list = (store[addr] || []).filter(id => !drop.has(Number(id)));
store[addr] = list;
try { writeFileSync(MY_PLANS_FILE, JSON.stringify(store), 'utf8'); } catch {}
}
/**
* RPC-first ownership check for the active wallet's plan list. Returns the
* subset of `planIds` actually owned by `getProvAddr()` and prunes the rest
* from `my-plans.json` so the UI never offers them again.
*
* Cached for 60s under `myPlansOwned:<provAddr>` to avoid hitting RPC on
* every dashboard refresh.
*/
/**
* Pre-flight ownership check for any TX that names a `planId`. RPC-first.
* Returns null on success, or an Express-friendly `{ status, error }` object
* to short-circuit the handler. Prevents broadcasting a doomed
* "address … is not authorized" TX (and burning gas) when the user's
* `my-plans.json` lists a plan they don't actually own.
*/
async function assertPlanOwnership(planId) {
if (!planId) return { status: 400, error: 'planId is required' };
const myProv = getProvAddr();
if (!myProv) return { status: 401, error: 'Wallet not loaded' };
// Resolve the plan's prov_address with RPC first, LCD fallback when RPC
// returns null (the SDK's rpcQueryPlan swallows ALL errors as null —
// transient blip vs missing plan are indistinguishable, so we MUST verify
// via LCD before allowing the TX, or doomed "is not authorized" broadcasts
// sneak through and burn gas).
let provAddress = null;
try {
const client = await getRpcClient();
if (client) {
const plan = await rpcQueryPlan(client, planId);
if (plan?.prov_address) provAddress = plan.prov_address;
}
} catch (e) {
console.warn(`[ownership] RPC ownership probe threw for plan ${planId}: ${e.message}`);
}
if (!provAddress) {
try {
const lcdPlan = await lcd(`/sentinel/plan/v3/plans/${planId}`);
if (lcdPlan?.plan?.prov_address) provAddress = lcdPlan.plan.prov_address;
} catch (e) {
console.warn(`[ownership] LCD ownership probe failed for plan ${planId}: ${e.message} — allowing TX (chain will validate)`);
return null;
}
}
if (!provAddress) {
// Both RPC and LCD failed to return a prov_address. Don't block —
// could be a brand-new plan or a transient outage. Chain will reject
// if foreign.
console.warn(`[ownership] No prov_address resolved for plan ${planId} via RPC or LCD — allowing TX`);
return null;
}
if (provAddress !== myProv) {
dropMyPlanIds([planId]);
return {
status: 403,
error: `Plan ${planId} is owned by ${provAddress}, not your wallet (${myProv}). It has been removed from your plan list.`,
};
}
return null;
}
async function filterOwnedPlanIds(planIds) {
if (!planIds || planIds.length === 0) return [];
const myProv = getProvAddr();
if (!myProv) return [];
return cached(`myPlansOwned:${myProv}:${planIds.slice().sort().join(',')}`, 60_000, async () => {
const client = await getRpcClient();
if (!client) {
// No RPC — can't make ownership decisions. Return list as-is, do not
// prune. Better to show possibly-stale plans than to nuke the list on
// a transient outage.
return planIds.map(Number).sort((a, b) => a - b);
}
const kept = [];
const foreign = [];
await Promise.all(planIds.map(async (id) => {
// RPC first.
let provAddress = null;
try {
const p = await rpcQueryPlan(client, id);
if (p?.prov_address) provAddress = p.prov_address;
} catch {}
// LCD fallback when RPC returned null (could be transient OR foreign).
if (!provAddress) {
try {
const lcdPlan = await lcd(`/sentinel/plan/v3/plans/${id}`);
if (lcdPlan?.plan?.prov_address) provAddress = lcdPlan.plan.prov_address;
} catch {
// Both queries failed — indeterminate, keep optimistically.
kept.push(Number(id));
return;
}
}
if (!provAddress) {
// Both RPC and LCD couldn't resolve — indeterminate, keep.
kept.push(Number(id));
return;
}
if (provAddress === myProv) kept.push(Number(id));
else foreign.push(Number(id));
}));
if (foreign.length) {
console.log(`[ownership] Pruning ${foreign.length} confirmed foreign plan(s) from my-plans.json: ${foreign.join(', ')}`);
dropMyPlanIds(foreign);
}
return kept.sort((a, b) => a - b);
});
}
// ─── Privy Cosmos Wallet Persistence ──────────────────────────────────────────
// Maps Privy userId → { walletId, pubkeyB64, sent1Addr } so repeat logins from
// the same email reuse the same Privy server-custody cosmos wallet (and
// therefore the same sent1 address) instead of provisioning a fresh one each
// session. Stored on disk via DATA_DIR; safe to commit no secrets here — the
// privkey lives inside Privy's enclave.
const PRIVY_WALLETS_FILE = join(DATA_DIR, 'privy-wallets.json');
function readPrivyWalletStore() {
try {
if (!existsSync(PRIVY_WALLETS_FILE)) return {};
const parsed = JSON.parse(readFileSync(PRIVY_WALLETS_FILE, 'utf8'));
return parsed && typeof parsed === 'object' ? parsed : {};
} catch (err) {
console.error('Failed to load privy-wallets.json:', err.message);
return {};
}
}
function lookupPrivyWallet(userId) {
if (!userId) return null;
const store = readPrivyWalletStore();
return store[userId] || null;
}
function lookupPrivyWalletByAddr(sent1Addr) {
if (!sent1Addr) return null;
const store = readPrivyWalletStore();
for (const [userId, entry] of Object.entries(store)) {
if (entry?.sent1Addr === sent1Addr) return { userId, ...entry };
}
return null;
}
function savePrivyWallet(userId, entry) {
if (!userId || !entry?.walletId) return;
const store = readPrivyWalletStore();
store[userId] = entry;
try { writeFileSync(PRIVY_WALLETS_FILE, JSON.stringify(store), 'utf8'); }
catch (err) { console.error('Failed to save privy-wallets.json:', err.message); }
}
// ─── Node Cache (SDK scan) ────────────────────────────────────────────────────
const NODE_CACHE_FILE = join(DATA_DIR, 'nodes-cache.json');
let nodeCache = { nodes: [], ts: 0, scanning: false };
let scanProgress = { total: 0, probed: 0, online: 0 };
function loadNodeCacheFromDisk() {
try {
if (!existsSync(NODE_CACHE_FILE)) return;
const d = JSON.parse(readFileSync(NODE_CACHE_FILE, 'utf8'));
if (d.nodes && d.nodes.length) {
const ageMs = Date.now() - (d.ts || 0);
// Only seed cache if fresh (within TTL). Stale on-disk data is discarded —
// we'd rather scan fresh than serve stale counts as "on-chain truth".
if (ageMs < NODE_CACHE_TTL) {
nodeCache.nodes = d.nodes;
nodeCache.ts = d.ts || 0;
console.log(`Seeded node cache from disk: ${d.nodes.length} nodes (age ${Math.round(ageMs / 1000)}s, will refresh in background)`);
} else {
console.log(`Disk node cache is stale (age ${Math.round(ageMs / 1000)}s > TTL ${NODE_CACHE_TTL / 1000}s) — discarding, will rescan`);
}
}
} catch (err) {
console.error('Failed to load node cache from disk:', err.message);
}
}
function saveNodeCacheToDisk(nodes) {
try { writeFileSync(NODE_CACHE_FILE, JSON.stringify({ nodes, ts: Date.now() }), 'utf8'); }
catch (err) { console.error('Failed to save node cache to disk:', err.message); }
}
loadNodeCacheFromDisk();
// Always kick a fresh scan on startup so the disk seed is replaced with on-chain truth ASAP.
runNodeScan().catch(err => console.error('Initial node scan failed:', err.message));
// Adapter: handles both shapes simultaneously —
// chain catalog (snake_case: gigabyte_prices, remote_url, no country)
// probe-enriched (camelCase: gigabytePrices, remoteUrl, country, city, etc.)
function nodeCacheToAllNodes(raw) {
return raw.map(n => {
const gbPrices = n.gigabytePrices || n.gigabyte_prices || [];
const hrPrices = n.hourlyPrices || n.hourly_prices || [];
const gbPrice = gbPrices.find(p => p.denom === 'udvpn');
const hrPrice = hrPrices.find(p => p.denom === 'udvpn');
return {
address: n.address,
remoteUrl: n.remoteUrl || n.remote_url || '',
gbPriceUdvpn: gbPrice ? parseInt(gbPrice.quote_value) : 0,
hrPriceUdvpn: hrPrice ? parseInt(hrPrice.quote_value) : 0,
status: 'active',
protocol: n.serviceType || null,
country: n.country || n.location?.country || null,
city: n.city || n.location?.city || null,
moniker: n.moniker || null,
speedMbps: null,
pass15: false,
pass10: false,
peers: n.peers ?? null,
};
});
}
// Two-phase scan:
// Phase 1 (fast): chain catalog via fetchAllNodes — every active node on chain.
// Cache populated with truth immediately. No probe filtering.
// Phase 2 (background): probe-enrich for country/city/protocol on top of catalog.
// Successful probes overlay enrichment fields; failures keep chain entry.
async function runNodeScan() {
if (nodeCache.scanning) return;
nodeCache.scanning = true;
scanProgress = { total: 0, probed: 0, online: 0 };
console.log('Starting node scan: phase 1 (chain catalog)...');
try {
// Pull the full chain catalog via RPC directly. SDK's fetchAllNodes()
// hardcodes limit=500 via fetchActiveNodes default — that's why we were
// missing half the network. Go straight to rpcQueryNodes with limit=10000.
const rpc = await getRpcClient();
const rawNodes = await rpcQueryNodes(rpc, { status: 1, limit: 10000 });
// Resolve remote URLs and filter to nodes that accept udvpn.
const catalog = rawNodes
.map(n => {
const addrs = n.remote_addrs || [];
const first = addrs[0];
n.remote_url = first ? (first.startsWith('http') ? first : `https://${first}`) : null;
return n;
})
.filter(n => n.remote_url && (n.gigabyte_prices || []).some(p => p.denom === 'udvpn'));
// Preserve prior enrichment (country/city/moniker/serviceType) across catalog
// refreshes — otherwise the country dropdown empties for the duration of phase 2.
const priorByAddr = new Map((nodeCache.nodes || []).map(n => [n.address, n]));
const seeded = catalog.map(n => {
const prior = priorByAddr.get(n.address);
if (!prior) return n;
return {
...n,
gigabytePrices: prior.gigabytePrices || prior.gigabyte_prices,
hourlyPrices: prior.hourlyPrices || prior.hourly_prices,
serviceType: prior.serviceType,
country: prior.country,
city: prior.city,
moniker: prior.moniker,
peers: prior.peers,
};
});
nodeCache = { nodes: seeded, ts: Date.now(), scanning: false };
saveNodeCacheToDisk(seeded);
console.log(`Phase 1 complete: ${catalog.length} chain nodes cached (truth, unfiltered).`);
// Phase 2: best-effort enrichment for country/protocol labels.
// Runs in background; successful probes are merged into the cache as they complete.
enrichNodeCacheInBackground(catalog).catch(err => {
console.error('Phase 2 enrichment failed:', err.message);
});
} catch (e) {
console.error('Node scan failed:', e.message);
nodeCache.scanning = false;
}
}
let _enrichInflight = false;
async function enrichNodeCacheInBackground(catalog) {
if (_enrichInflight) return;
_enrichInflight = true;
console.log('Starting node scan: phase 2 (background enrichment)...');
try {
const enriched = await sdkEnrichNodes(catalog, {
concurrency: 30,
onProgress: (p) => { scanProgress = { total: p.total, probed: p.done, online: p.enriched }; },
});
// Merge: chain catalog stays as base; enriched entries overlay country/serviceType/etc.
const enrichedByAddr = new Map(enriched.map(e => [e.address, e]));
const merged = catalog.map(n => {
const e = enrichedByAddr.get(n.address);
if (!e) return n;
return {
...n,
gigabytePrices: e.gigabytePrices || n.gigabyte_prices,
hourlyPrices: e.hourlyPrices || n.hourly_prices,
serviceType: e.serviceType,
country: e.country,
city: e.city,
moniker: e.moniker,
peers: e.peers,
};
});
nodeCache.nodes = merged;
nodeCache.ts = Date.now();
saveNodeCacheToDisk(merged);
console.log(`Phase 2 complete: ${enriched.length}/${catalog.length} nodes enriched with country/protocol.`);
} finally {
_enrichInflight = false;
}
}
async function fetchAllNodes() {
const now = Date.now();
if (nodeCache.nodes.length > 0 && (now - nodeCache.ts) < NODE_CACHE_TTL) {
return nodeCacheToAllNodes(nodeCache.nodes);
}
if (nodeCache.scanning) {
return nodeCacheToAllNodes(nodeCache.nodes);
}
if (nodeCache.nodes.length > 0) {
runNodeScan(); // background refresh
return nodeCacheToAllNodes(nodeCache.nodes);
}
await runNodeScan();
return nodeCacheToAllNodes(nodeCache.nodes);
}
// ─── Plan Helpers ─────────────────────────────────────────────────────────────
async function discoverPlanIds() {
const ids = new Set();
// Fetch RPC client once outside the loop — reused for every probe.
let rpc = null;
try { rpc = await getRpcClient(); } catch (_) { rpc = null; }
for (let batch = 0; batch < 10; batch++) {
const checks = [];
for (let i = batch * 10 + 1; i <= (batch + 1) * 10; i++) {
checks.push((async (planId) => {
// RPC-first: if RPC returns a non-empty array the plan exists.
// Empty array is ambiguous (truly empty OR not-on-chain) — fall back to LCD count_total.
if (rpc) {
try {
const result = await rpcQuerySubscriptionsForPlan(rpc, planId, { limit: 1 });
if (result && result.length > 0) { ids.add(planId); return; }
} catch (err) {
console.log(`[RPC] discoverPlanIds probe ${planId} failed: ${err.message} — LCD fallback`);
}
}
// LCD fallback — count_total is authoritative for empty-vs-nonexistent distinction.
await lcd(`/sentinel/subscription/v3/plans/${planId}/subscriptions?pagination.limit=1&pagination.count_total=true`)
.then(d => {
const total = parseInt(d.pagination?.total || '0');
if (total > 0) ids.add(planId);
})
.catch(() => {});
})(i));
}
await Promise.all(checks);
}
return [...ids].sort((a, b) => a - b);
}
async function getUniqueWallets(planId) {
const wallets = new Set();
// RPC-first: single protobuf call returns the full set (~912x faster than paginated LCD).
try {
const rpc = await getRpcClient();
if (rpc) {
const subs = await rpcQuerySubscriptionsForPlan(rpc, planId, { limit: 10000 });
for (const s of subs) wallets.add(s.acc_address);
return wallets.size;
}
} catch (err) {
console.log(`[RPC] getUniqueWallets(${planId}) failed: ${err.message} — LCD fallback`);
}
// LCD fallback
let nextKey = undefined;
let pages = 0;
const MAX_PAGES = 20;
do {
const keyParam = nextKey ? `&pagination.key=${encodeURIComponent(nextKey)}` : '';
const d = await lcd(`/sentinel/subscription/v3/plans/${planId}/subscriptions?pagination.limit=500${keyParam}`);
for (const s of d.subscriptions || []) {
wallets.add(s.acc_address);
}
nextKey = d.pagination?.next_key || null;
pages++;
} while (nextKey && pages < MAX_PAGES);
return wallets.size;
}
// Retry a thunk up to `attempts` times with exponential backoff.
// Used by getPlanStats so a transient RPC/LCD blip doesn't silently
// drop a plan from the my-plans response.
async function _retry(thunk, { attempts = 3, baseMs = 400, label = 'op' } = {}) {
let lastErr;
for (let i = 0; i < attempts; i++) {
try {
return await thunk();
} catch (err) {
lastErr = err;
if (i < attempts - 1) {
const wait = baseMs * Math.pow(2, i);
console.log(`[retry] ${label} attempt ${i + 1}/${attempts} failed (${err.message}); retrying in ${wait}ms`);
await new Promise(r => setTimeout(r, wait));
}
}
}
throw lastErr;
}
async function getPlanStats(planId) {
// Cache only successful results — retry transient failures up to 3x before
// giving up. Otherwise a single RPC blip caches a null for 2 minutes and
// the plan disappears from the UI even after the chain recovers.
return cached(`planStats:${planId}`, 120_000, () =>
_retry(() => _getPlanStatsImpl(planId), { attempts: 3, baseMs: 500, label: `getPlanStats(${planId})` })
);
}
async function _getPlanStatsImpl(planId) {
// Fetch RPC client once for this call — shared by RPC-first paths below.
let rpc = null;
try { rpc = await getRpcClient(); } catch (_) { rpc = null; }
// Single RPC call replaces two LCD calls (count_total + reverse-paginated 200).
// Pulls up to 10000 subs in one shot; we derive total + sample from that array.
// Falls back to LCD only if RPC fails or is unavailable.
const [subsResult, nodesData, planRecord] = await Promise.all([
(async () => {
if (rpc) {
try {
const subs = await rpcQuerySubscriptionsForPlan(rpc, planId, { limit: 10000 });
return { source: 'rpc', subs };
} catch (err) {
console.log(`[RPC] _getPlanStatsImpl subs(${planId}) failed: ${err.message} — LCD fallback`);
}
}
// LCD fallback: two calls — count_total + reverse sample.
const [countD, latestD] = await Promise.all([
lcd(`/sentinel/subscription/v3/plans/${planId}/subscriptions?pagination.limit=1&pagination.count_total=true`).catch(() => ({})),
lcd(`/sentinel/subscription/v3/plans/${planId}/subscriptions?pagination.limit=200&pagination.reverse=true`).catch(() => ({})),
]);
return { source: 'lcd', countTotal: parseInt(countD.pagination?.total || '0'), subs: latestD.subscriptions || [] };
})(),
(async () => {
if (rpc) {
try {
const nodes = await rpcQueryNodesForPlan(rpc, planId, { status: 1, limit: 5000 });
if (nodes) return { nodes };
} catch (err) {
console.log(`[RPC] _getPlanStatsImpl nodes(${planId}) failed: ${err.message} — LCD fallback`);
}
}
return lcd(`/sentinel/node/v3/plans/${planId}/nodes?pagination.limit=500`).catch(() => ({ nodes: [] }));
})(),
(async () => {
if (rpc) {
try {
const p = await rpcQueryPlan(rpc, planId);
if (p) return p;
} catch (err) {
console.log(`[RPC] _getPlanStatsImpl plan(${planId}) failed: ${err.message} — LCD fallback`);
}
}
try {
const lp = await lcd(`/sentinel/plan/v3/plans/${planId}`);
return lp?.plan || null;
} catch { return null; }
})(),
]);
// Normalize RPC sub fields to match LCD-shaped consumers downstream.
// RPC: status=1 (int, 1=active), renewal_price_policy=int. LCD: 'active' / 'no'|'yes'.
const normSubs = (subsResult.subs || []).map(s => ({
...s,
status: typeof s.status === 'number' ? (s.status === 1 ? 'active' : 'inactive') : s.status,
renewal_price_policy: typeof s.renewal_price_policy === 'number'
? (s.renewal_price_policy === 1 ? 'no' : s.renewal_price_policy === 2 ? 'yes' : 'unknown')
: (s.renewal_price_policy || 'unknown'),
}));
// Sort newest-first by start_at to mirror reverse-pagination semantics.
normSubs.sort((a, b) => new Date(b.start_at || 0) - new Date(a.start_at || 0));
const totalSubs = subsResult.source === 'rpc' ? normSubs.length : (subsResult.countTotal || 0);
const totalNodes = (nodesData.nodes || []).length;
const allSampleSubs = normSubs.slice(0, 200);
const sampleSubs = allSampleSubs.filter(s => s.acc_address !== getAddr());
const sampleWallets = new Set(sampleSubs.map(s => s.acc_address));
const ownSubs = allSampleSubs.length - sampleSubs.length;
const sample = sampleSubs[0] || allSampleSubs[0];
const renewalPolicy = sample?.renewal_price_policy || 'unknown';
// Authoritative price comes from the plan record (set at creation, immutable).
// Subscription samples are only used as a last-resort fallback when the plan
// record didn't load — pricing must NOT silently fall back to zero just
// because the plan has no subscribers yet.
const planPrices = Array.isArray(planRecord?.prices) ? planRecord.prices : [];
const planPrice = planPrices[0] || null;
const price = planPrice
? { denom: planPrice.denom, quote_value: planPrice.quote_value, base_value: planPrice.base_value }
: (sample?.price || { denom: 'udvpn', quote_value: '0', base_value: '0' });
const now = new Date();
let activeSubs = 0;
let inactiveSubs = 0;
for (const s of sampleSubs) {
if (s.status === 'active' && new Date(s.inactive_at) > now) activeSubs++;
else inactiveSubs++;
}
const dates = sampleSubs.map(s => new Date(s.start_at)).sort((a, b) => a - b);
const earliestStart = dates[0]?.toISOString() || null;
const latestStart = dates[dates.length - 1]?.toISOString() || null;
// Duration from the plan record (seconds → days). Fall back to the
// sample-derived duration only when the plan record didn't load.
let durationDays = null;
if (planRecord?.duration != null) {
const durSec = typeof planRecord.duration === 'string'
? parseInt(planRecord.duration)
: Number(planRecord.duration);
if (Number.isFinite(durSec) && durSec > 0) {
durationDays = Math.round(durSec / 86400);
}
}
if (durationDays == null && sample) {
const start = new Date(sample.start_at);
const end = new Date(sample.inactive_at);
durationDays = Math.round((end - start) / (1000 * 60 * 60 * 24));
}
const quoteNum = parseInt(price.quote_value || '0');
return {
planId,
totalSubscriptions: Math.max(0, totalSubs - ownSubs),
totalNodes,
uniqueWalletsSample: sampleWallets.size,
price: {
denom: price.denom,
quoteValue: price.quote_value,
baseValue: price.base_value,
dvpnAmount: price.denom === 'udvpn' ? (quoteNum / 1e6) : null,
},
prices: planPrices.map(p => ({
denom: p.denom,
quoteValue: p.quote_value,
baseValue: p.base_value,
dvpnAmount: p.denom === 'udvpn' ? (parseInt(p.quote_value || '0') / 1e6) : null,
})),
renewalPolicy,
activeSubs,
inactiveSubs,
sampleSize: sampleSubs.length,
durationDays,
earliestStart,
latestStart,
estimatedTotalP2p: price.denom === 'udvpn' ? (totalSubs * quoteNum / 1e6) : null,
};
}
async function getNodesForPlan(planId) {
const nodes = [];
// RPC-first
try {
const rpc = await getRpcClient();
if (rpc) {
const rpcNodes = await rpcQueryNodesForPlan(rpc, planId, { status: 1, limit: 5000 });
for (const n of rpcNodes) {
const rawAddr = (n.remote_addrs || [])[0] || '';
nodes.push({
address: n.address,
remoteUrl: rawAddr ? (rawAddr.startsWith('http') ? rawAddr : `https://${rawAddr}`) : '',
gigabytePrices: n.gigabyte_prices,
hourlyPrices: n.hourly_prices,
status: n.status === 1 ? 'active' : 'inactive',
inactiveAt: null,
statusAt: null,
});
}
return nodes;
}
} catch (err) {
console.log(`[RPC] getNodesForPlan(${planId}) failed: ${err.message} — LCD fallback`);
}
// LCD fallback
let nextKey = undefined;
do {
const keyParam = nextKey ? `&pagination.key=${encodeURIComponent(nextKey)}` : '';
const d = await lcd(`/sentinel/node/v3/plans/${planId}/nodes?pagination.limit=100${keyParam}`);
for (const n of d.nodes || []) {
const rawAddr = (n.remote_addrs || [])[0] || '';
nodes.push({
address: n.address,
remoteUrl: rawAddr ? (rawAddr.startsWith('http') ? rawAddr : `https://${rawAddr}`) : '',
gigabytePrices: n.gigabyte_prices,
hourlyPrices: n.hourly_prices,
status: n.status === 'active' || n.status === 1 ? 'active' : 'inactive',
inactiveAt: n.inactive_at || null,
statusAt: n.status_at || null,
});
}
nextKey = d.pagination?.next_key || null;
} while (nextKey);
return nodes;
}
async function getProviders() {
const d = await lcd('/sentinel/provider/v2/providers?pagination.limit=100');
return (d.providers || []).map(p => ({
address: p.address,
name: p.name,
identity: p.identity,
website: p.website,
description: p.description,
status: p.status,
}));
}
// ─── Analytics Helpers ────────────────────────────────────────────────────────
async function getAllNodeInfo() {
const nodeMap = {};
// RPC-first: single call returns full list, no pagination needed.
try {
const rpc = await getRpcClient();
if (rpc) {
const nodes = await rpcQueryNodes(rpc, { status: 1, limit: 10000 });
for (const n of nodes) {
const hourlyPrice = (n.hourly_prices || []).find(p => p.denom === 'udvpn');
const gbPrice = (n.gigabyte_prices || []).find(p => p.denom === 'udvpn');
nodeMap[n.address] = {
hourlyUdvpn: hourlyPrice ? parseInt(hourlyPrice.quote_value) : 0,
gbUdvpn: gbPrice ? parseInt(gbPrice.quote_value) : 0,
};
}
console.log(`[RPC] getAllNodeInfo: ${Object.keys(nodeMap).length} nodes loaded`);
return nodeMap;
}
} catch (err) {
console.log(`[RPC] getAllNodeInfo failed (${err.message}), falling back to LCD`);
}
// LCD fallback: paginated scan.
let nextKey = undefined;
do {
const keyParam = nextKey ? `&pagination.key=${encodeURIComponent(nextKey)}` : '';
const d = await lcd(`/sentinel/node/v3/nodes?status=1&pagination.limit=500${keyParam}`);
for (const n of d.nodes || []) {
const hourlyPrice = (n.hourly_prices || []).find(p => p.denom === 'udvpn');
const gbPrice = (n.gigabyte_prices || []).find(p => p.denom === 'udvpn');
nodeMap[n.address] = {
hourlyUdvpn: hourlyPrice ? parseInt(hourlyPrice.quote_value) : 0,
gbUdvpn: gbPrice ? parseInt(gbPrice.quote_value) : 0,
};
}
nextKey = d.pagination?.next_key || null;
} while (nextKey);
return nodeMap;
}
async function scanSessions() {
const nodes = {};
let nextKey = undefined;
let pages = 0;
let totalScanned = 0;
// No chain-wide RPC sessions query available — LCD is the only path
do {
const keyParam = nextKey ? `&pagination.key=${encodeURIComponent(nextKey)}` : '';
const d = await lcd(`/sentinel/session/v3/sessions?pagination.limit=500${keyParam}`);
const sessions = d.sessions || [];
for (const s of sessions) {
const b = s.base_session || {};
const nodeAddr = b.node_address;
if (!nodeAddr) continue;
if (!nodes[nodeAddr]) {
nodes[nodeAddr] = { users: new Set(), dlBytes: 0, ulBytes: 0, sessions: 0, totalDurSec: 0 };
}