-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend-server.js
More file actions
4528 lines (4116 loc) · 197 KB
/
Copy pathbackend-server.js
File metadata and controls
4528 lines (4116 loc) · 197 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
require('dotenv').config({ path: __dirname + '/.env' });
const _envCheck = { moralis: !!process.env.MORALIS_KEY, alchemy: !!process.env.ALCHEMY_KEY, cwd: process.cwd(), dir: __dirname };
console.log('🔑 ENV check:', JSON.stringify(_envCheck));
const express = require('express');
const cors = require('cors');
// Use Node's built-in fetch (undici) — avoids node-fetch v2's "Premature close"
// bug on Node 24.17+ keep-alive sockets. Falls back to node-fetch only on <18.
const fetch = globalThis.fetch || ((...args) => import('node-fetch').then(m => m.default(...args)));
const path = require('path');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const {
EVM_CHAINS: SCANNER_EVM_CHAINS,
DEFAULT_CHAINS: SCANNER_CHAINS,
PROFILE_WALLET_MAP,
validateProfileWalletAddress,
normalizeProfileWalletAddress,
} = require('./public/chain-catalog');
const { createNonEvmScanner } = require('./non-evm-scanner');
const {
isUuid, orderedFriendPair, normalizeChatContent,
summarizeChatUnread, chatConversationKey, WORLD_CONVERSATION,
} = require('./chat-service');
const { resolveWalletSession } = require('./auth-session');
const { createPrecompiledPage, COMPILED_PREFIX } = require('./precompile-page');
const { createSwapService, registerSwapRoutes, withSwapIdentity } = require('./swap-service');
const { createExchangeService, registerExchangeRoutes } = require('./exchange-service');
// ─── Supabase (optional — only active if env vars are set) ────────────────────
let supabase = null;
if (process.env.SUPABASE_URL && process.env.SUPABASE_SERVICE_KEY) {
const { createClient } = require('@supabase/supabase-js');
supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);
console.log('✅ Supabase connected');
} else {
console.warn('⚠️ SUPABASE_URL / SUPABASE_SERVICE_KEY missing — profile features disabled');
}
// ─── Ethers for EVM signature verification ────────────────────────────────────
let ethersVerify = null;
let ethersLib = null;
try {
const { ethers } = require('ethers');
ethersLib = ethers;
// Works for both ethers v5 (utils.verifyMessage) and v6 (verifyMessage)
ethersVerify = ethers.verifyMessage
? (msg, sig) => ethers.verifyMessage(msg, sig)
: (msg, sig) => ethers.utils.verifyMessage(msg, sig);
console.log('✅ ethers loaded for EVM signature verification');
} catch (e) { console.warn('⚠️ ethers not installed — EVM sig verification skipped'); }
// ─── Abstract Global Wallet: derive smart account address from EOA ────────────
// Uses the AGW factory contract on Abstract mainnet — no extra packages needed.
// Docs: https://docs.abs.xyz/abstract-global-wallet/agw-client/getSmartAccountAddressFromInitialSigner
const AGW_FACTORY = '0xe86Bf72715dF28a0b7c3C8F596E7fE05a22A139c';
const AGW_FACTORY_ABI = ['function getAddressForSalt(bytes32 salt) view returns (address)'];
const ABSTRACT_RPC = 'https://api.mainnet.abs.xyz';
const deriveAGWAddress = async (eoaAddress) => {
if (!ethersLib) return null;
try {
// ethers v5 vs v6 compat
const provider = ethersLib.JsonRpcProvider
? new ethersLib.JsonRpcProvider(ABSTRACT_RPC) // v6
: new ethersLib.providers.JsonRpcProvider(ABSTRACT_RPC); // v5
const factory = new ethersLib.Contract(AGW_FACTORY, AGW_FACTORY_ABI, provider);
// Salt = keccak256(toBytes(eoaAddress)) — same as agw-client source
const salt = ethersLib.keccak256
? ethersLib.keccak256(ethersLib.getBytes(eoaAddress)) // v6
: ethersLib.utils.keccak256(ethersLib.utils.arrayify(eoaAddress)); // v5
const agwAddress = await factory.getAddressForSalt(salt);
console.log(`⚡ AGW address derived for ${eoaAddress.slice(0,10)}… → ${agwAddress}`);
return agwAddress;
} catch (e) {
console.warn('⚠️ AGW address derivation failed:', e.message);
return null;
}
};
// ─── SimpleWebAuthn for passkey (WebAuthn) sign-in ────────────────────────────
// Optional, like every other verifier here: if the dep is missing the passkey
// routes report themselves unavailable and the UI hides the buttons, rather
// than the server failing to boot.
let webauthn = null;
try { webauthn = require('@simplewebauthn/server'); console.log('✅ @simplewebauthn/server loaded'); }
catch (e) { console.warn('⚠️ @simplewebauthn/server not installed — passkey sign-in disabled'); }
// ─── TweetNaCl for Solana signature verification ──────────────────────────────
let nacl = null;
try { nacl = require('tweetnacl'); console.log('✅ tweetnacl loaded'); }
catch (e) { console.warn('⚠️ tweetnacl not installed — Solana sig verification skipped'); }
// ─── Inline base58 decoder (Solana pubkey decode, no heavy dep) ───────────────
const BASE58_ALPHA = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const base58Decode = (input) => {
let bytes = [0];
for (const char of input) {
const val = BASE58_ALPHA.indexOf(char);
if (val < 0) throw new Error('Invalid base58 char: ' + char);
let carry = val;
for (let i = 0; i < bytes.length; i++) {
carry += bytes[i] * 58; bytes[i] = carry & 0xff; carry >>= 8;
}
while (carry > 0) { bytes.push(carry & 0xff); carry >>= 8; }
}
for (const char of input) { if (char !== '1') break; bytes.push(0); }
return Buffer.from(bytes.reverse());
};
const JWT_SECRET = process.env.JWT_SECRET || 'chainlens-dev-secret-CHANGE-IN-PRODUCTION';
const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:10000';
// ─── WebAuthn relying-party identity ─────────────────────────────────────────
// rpID is the DOMAIN a passkey is bound to, and it is permanent: changing it
// orphans every passkey already registered. Default to the registrable domain
// (apex, no "www.") so a passkey made on www.chainlensnft.info still works on
// chainlensnft.info and vice-versa — the browser accepts an rpID that is the
// page origin or a registrable suffix of it.
const RP_NAME = 'ChainLens';
const RP_PROD_DOMAIN = 'chainlensnft.info';
const RP_ID = process.env.WEBAUTHN_RP_ID || (() => {
let host = null;
try { host = new URL(FRONTEND_URL).hostname.replace(/^www\./, ''); } catch { /* malformed */ }
// FRONTEND_URL defaults to http://localhost:10000 when unset, so a deploy that
// forgot it would bind every passkey to "localhost" — credentials that can
// never be used on the real site, and unfixable afterwards. In production the
// real domain always wins over that fallback.
const isLoopback = !host || host === 'localhost' || host === '127.0.0.1';
if (isLoopback && process.env.NODE_ENV === 'production') return RP_PROD_DOMAIN;
return host || RP_PROD_DOMAIN;
})();
// Origins the assertion may legitimately come from. Unlike rpID this is an
// exact match, so both hostnames must be listed explicitly.
const RP_ORIGINS = (() => {
const fromEnv = (process.env.WEBAUTHN_ORIGINS || '')
.split(',').map(s => s.trim().replace(/\/+$/, '')).filter(Boolean);
if (fromEnv.length) return fromEnv;
const set = new Set();
try { set.add(new URL(FRONTEND_URL).origin); } catch { /* malformed FRONTEND_URL */ }
if (RP_ID !== 'localhost') { set.add(`https://${RP_ID}`); set.add(`https://www.${RP_ID}`); }
return [...set];
})();
if (webauthn) {
console.log(`🔐 Passkey RP: id=${RP_ID} origins=${RP_ORIGINS.join(' ')}`);
// rpID is baked into every credential and cannot be changed later without
// orphaning them all, so a mismatch between it and the site's own origins is
// worth shouting about rather than discovering months later.
if (!RP_ORIGINS.some(o => { try { return new URL(o).hostname === RP_ID || new URL(o).hostname.endsWith(`.${RP_ID}`); } catch { return false; } })) {
console.error(`❌ WEBAUTHN_RP_ID "${RP_ID}" does not match any allowed origin (${RP_ORIGINS.join(' ')}) — passkey ceremonies will be rejected by the browser. Set WEBAUTHN_RP_ID / WEBAUTHN_ORIGINS.`);
}
}
// ─── In-memory nonce store (auto-cleaned every 5 min) ────────────────────────
const _authNonces = {}; // { address_lower: { nonce, expires } }
const _oauthStates = {}; // { state: { expires } }
// { ceremonyId: { challenge, userId|null, expires } } — a WebAuthn challenge is
// single-use and short-lived; holding it server-side is what stops a replay.
const _passkeyChallenges = {};
setInterval(() => {
const now = Date.now();
Object.keys(_authNonces).forEach(k => { if (_authNonces[k].expires < now) delete _authNonces[k]; });
Object.keys(_oauthStates).forEach(k => { if (_oauthStates[k].expires < now) delete _oauthStates[k]; });
Object.keys(_passkeyChallenges).forEach(k => { if (_passkeyChallenges[k].expires < now) delete _passkeyChallenges[k]; });
}, 5 * 60 * 1000);
// ─── Auth middleware ──────────────────────────────────────────────────────────
const requireAuth = (req, res, next) => {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) return res.status(401).json({ error: 'No token provided' });
try {
req.user = jwt.verify(token, JWT_SECRET);
next();
} catch (e) { res.status(401).json({ error: 'Invalid or expired token' }); }
};
// ─── DB helpers ──────────────────────────────────────────────────────────────
const dbUpsertUser = async ({ provider, provider_id, display_name, avatar_url, email }) => {
if (!supabase) return null;
const { data, error } = await supabase
.from('cl_users')
.upsert({ provider, provider_id, display_name, avatar_url, email },
{ onConflict: 'provider,provider_id' })
.select().single();
if (error) throw error;
return data;
};
const dbGetUserById = async (id) => {
if (!supabase) return null;
const { data } = await supabase
.from('cl_users')
.select('*, cl_wallets(*), cl_linked_accounts(*)')
.eq('id', id).single();
return data;
};
// Upsert a social login record linked to a user_id
const dbLinkSocialAccount = async (userId, { provider, provider_id, display_name, avatar_url, email }) => {
if (!supabase) return null;
const { data, error } = await supabase
.from('cl_linked_accounts')
.upsert(
{ user_id: userId, provider, provider_id, display_name, avatar_url, email },
{ onConflict: 'provider,provider_id' }
)
.select().single();
if (error) throw error;
return data;
};
// Find an existing user who already has this social account linked
const dbFindUserBySocial = async (provider, provider_id) => {
if (!supabase) return null;
const { data } = await supabase
.from('cl_linked_accounts')
.select('user_id')
.eq('provider', provider)
.eq('provider_id', provider_id)
.single();
if (!data) return null;
return dbGetUserById(data.user_id);
};
const dbLinkWallet = async (userId, { chain, address, watch_only = false }) => {
if (!supabase) return null;
const { data, error } = await supabase
.from('cl_wallets')
.upsert({ user_id: userId, chain, address, watch_only, verified_at: new Date().toISOString() },
{ onConflict: 'user_id,address' })
.select().single();
if (error) throw error;
return data;
};
// ─── Passkey (cl_passkeys) helpers ───────────────────────────────────────────
// Every one of these can fail with "relation does not exist" until the operator
// runs sql/cl_passkeys.sql, so callers treat a throw as "passkeys unavailable"
// rather than letting it surface as a 500.
const dbListPasskeys = async (userId) => {
if (!supabase) return [];
const { data, error } = await supabase
.from('cl_passkeys')
.select('id, credential_id, transports, device_type, backed_up, label, created_at, last_used_at')
.eq('user_id', userId)
.order('created_at', { ascending: true });
if (error) throw error;
return data || [];
};
const dbFindPasskey = async (credentialId) => {
if (!supabase) return null;
const { data, error } = await supabase
.from('cl_passkeys')
.select('*')
.eq('credential_id', credentialId)
.maybeSingle();
if (error) throw error;
return data;
};
const dbInsertPasskey = async (userId, passkey) => {
if (!supabase) return null;
const { data, error } = await supabase
.from('cl_passkeys')
.insert({ user_id: userId, ...passkey })
.select().single();
if (error) throw error;
return data;
};
const dbTouchPasskey = async (id, counter) => {
if (!supabase) return;
await supabase.from('cl_passkeys')
.update({ counter, last_used_at: new Date().toISOString() })
.eq('id', id);
};
// Scoped to user_id so one account can never delete another's passkey.
const dbDeletePasskey = async (userId, id) => {
if (!supabase) return;
const { error } = await supabase.from('cl_passkeys')
.delete().eq('id', id).eq('user_id', userId);
if (error) throw error;
};
// ─── ChainLens Messenger helpers ─────────────────────────────────────────────
// Chat stays behind the existing ChainLens JWT boundary. The browser never
// talks to these Supabase tables directly; the service-role client below is the
// only database caller, and cl_chat.sql enables RLS with no client policies.
const CHAT_PROFILE_COLUMNS = 'id, display_name, avatar_url';
const CHAT_INITIAL_PAGE = 60;
const CHAT_POLL_PAGE = 100;
const dbGetChatEligibility = async (userId) => {
if (!supabase) return { eligible: false, walletLinked: false, socialLinked: false };
const [walletResult, socialResult] = await Promise.all([
supabase.from('cl_wallets')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.eq('watch_only', false),
supabase.from('cl_linked_accounts')
.select('id', { count: 'exact', head: true })
.eq('user_id', userId)
.in('provider', ['google', 'discord']),
]);
if (walletResult.error) throw walletResult.error;
if (socialResult.error) throw socialResult.error;
const walletLinked = (walletResult.count || 0) > 0;
const socialLinked = (socialResult.count || 0) > 0;
return { eligible: walletLinked && socialLinked, walletLinked, socialLinked };
};
const dbHydrateChatMessages = async (rows) => {
const messages = Array.isArray(rows) ? rows : [];
const ids = [...new Set(messages.map(row => row.user_id || row.sender_id).filter(Boolean))];
let profiles = [];
if (ids.length) {
const result = await supabase.from('cl_users').select(CHAT_PROFILE_COLUMNS).in('id', ids);
if (result.error) throw result.error;
profiles = result.data || [];
}
const byId = new Map(profiles.map(profile => [profile.id, profile]));
return messages.map(row => ({
id: row.id,
message_type: row.message_type,
content: row.content,
created_at: row.created_at,
author: byId.get(row.user_id || row.sender_id) || {
id: row.user_id || row.sender_id,
display_name: 'ChainLens user',
avatar_url: null,
},
}));
};
const dbFindFriendship = async (userId, otherUserId) => {
const [userLow, userHigh] = orderedFriendPair(userId, otherUserId);
const { data, error } = await supabase.from('cl_friendships')
.select('*').eq('user_low', userLow).eq('user_high', userHigh).maybeSingle();
if (error) throw error;
return data;
};
const dbGetAcceptedFriendship = async (userId, otherUserId) => {
const friendship = await dbFindFriendship(userId, otherUserId);
return friendship?.status === 'accepted' ? friendship : null;
};
const parseChatCursor = (value) => {
if (value === undefined || value === null || value === '') return null;
const cursor = Number(value);
if (!Number.isSafeInteger(cursor) || cursor < 0) throw new Error('Invalid message cursor');
return cursor;
};
const parseChatMessageId = (value) => {
const messageId = Number(value);
if (!Number.isSafeInteger(messageId) || messageId < 1) throw new Error('Invalid message ID');
return messageId;
};
// ─── Read cursors ────────────────────────────────────────────────────────────
// Unread state is server-side on purpose: the same account is signed in on the
// website, the desktop wallet, the extension and mobile, and reading a thread
// on one has to clear its badge on the rest.
const dmConversation = (friendshipId) => chatConversationKey(friendshipId);
const dbChatUnread = async (userId) => {
// Back-dates a brand-new account's cursors so months of history do not land
// as hundreds of unread on the first poll. No-ops after the first call — see
// cl_chat_seed_reads in sql/cl_chat.sql.
const seed = await supabase.rpc('cl_chat_seed_reads', { p_user_id: userId });
if (seed.error) throw seed.error;
const [unreadResult, pendingResult] = await Promise.all([
// One grouped join for every thread — see cl_chat_unread in sql/cl_chat.sql.
supabase.rpc('cl_chat_unread', { p_user_id: userId }),
supabase.from('cl_friendships')
.select('id', { count: 'exact', head: true })
.or(`user_low.eq.${userId},user_high.eq.${userId}`)
.eq('status', 'pending')
.neq('requested_by', userId),
]);
if (unreadResult.error) throw unreadResult.error;
if (pendingResult.error) throw pendingResult.error;
return summarizeChatUnread(unreadResult.data, pendingResult.count);
};
const chatMessageWindows = new Map();
const chatMessageAllowed = (userId) => {
const now = Date.now();
const recent = (chatMessageWindows.get(userId) || []).filter(time => now - time < 10_000);
if (recent.length >= 6) {
chatMessageWindows.set(userId, recent);
return false;
}
recent.push(now);
chatMessageWindows.set(userId, recent);
return true;
};
const chatRateCleanup = setInterval(() => {
const cutoff = Date.now() - 10_000;
for (const [userId, times] of chatMessageWindows) {
const recent = times.filter(time => time >= cutoff);
if (recent.length) chatMessageWindows.set(userId, recent);
else chatMessageWindows.delete(userId);
}
}, 60_000);
chatRateCleanup.unref();
const chatDbFailure = (res, error, fallback = 'Chat is temporarily unavailable') => {
console.error('ChainLens chat database error:', error);
if (error?.code === '42P01') {
return res.status(503).json({ error: 'Chat is not configured yet. Run sql/cl_chat.sql.' });
}
return res.status(500).json({ error: fallback });
};
const requireChatAccess = async (req, res, next) => {
if (!supabase) return res.status(503).json({ error: 'Supabase not configured' });
try {
const access = await dbGetChatEligibility(req.user.sub);
if (!access.eligible) {
return res.status(403).json({
error: 'Link at least one verified wallet and Google or Discord to use chat.',
...access,
});
}
req.chatAccess = access;
next();
} catch (error) {
chatDbFailure(res, error);
}
};
const app = express();
const PORT = process.env.PORT || 10000;
const SEARCH_WORKER_BASE_URL = process.env.SEARCH_WORKER_BASE_URL || 'https://chainlens-search.guildfordking.workers.dev';
const searchRateLimits = new Map();
app.set('trust proxy', 1);
app.use(cors());
// Profile photos are stored in the shared avatar_url field as either HTTPS URLs
// or compact image data URLs. Keep the cap narrow enough to prevent oversized
// requests while allowing the 2 MB client-side avatar limit plus base64 overhead.
app.use(express.json({ limit: '3mb' }));
// Homepage with its JSX compiled on the server, not by Babel in the visitor's
// browser (see precompile-page.js). Registered before express.static, which
// would otherwise answer '/' with the raw index.html. Falls back to that raw
// file on its own if the compile ever fails.
const precompiledPage = createPrecompiledPage(path.join(__dirname, 'public'));
precompiledPage.current(); // compile at boot, not on the first visitor
app.get(['/', '/index.html', '/magic-swap'], precompiledPage.sendPage);
app.get(`${COMPILED_PREFIX}*`, precompiledPage.sendAsset);
// Keep old bookmarks working; both swap modes now live on Magic Swap.
app.get(['/dex-swap', '/dex-swap.html'], (req, res) => res.redirect(302, '/magic-swap'));
app.use(express.static(path.join(__dirname, 'public')));
const searchRateLimit = (req, res, next) => {
const now = Date.now();
const windowMs = 60 * 1000;
const limit = 30;
const key = req.ip || req.socket.remoteAddress || 'unknown';
const current = searchRateLimits.get(key);
if (!current || now >= current.resetAt) {
searchRateLimits.set(key, { count: 1, resetAt: now + windowMs });
return next();
}
if (current.count >= limit) {
res.set('Retry-After', String(Math.ceil((current.resetAt - now) / 1000)));
return res.status(429).json({ error: 'Too many searches. Please wait a moment and try again.' });
}
current.count += 1;
next();
};
const searchRateLimitCleanup = setInterval(() => {
const now = Date.now();
for (const [key, value] of searchRateLimits) {
if (value.resetAt <= now) searchRateLimits.delete(key);
}
}, 5 * 60 * 1000);
searchRateLimitCleanup.unref();
const API_KEYS = {
alchemy: process.env.ALCHEMY_KEY,
blockfrost: process.env.BLOCKFROST_KEY,
helius: process.env.HELIUS_KEY,
unstoppable: process.env.UNSTOPPABLE_KEY,
dexhunter: process.env.DEXHUNTER_PARTNER_ID,
jupiter: process.env.JUPITER_API_KEY,
uniswap: process.env.UNISWAP_API_KEY,
zerion: process.env.ZERION_KEY,
moralis: process.env.MORALIS_KEY,
coingecko: process.env.COINGECKO_KEY,
coinmarketcap: process.env.COINMARKETCAP_API_KEY || process.env.CMC_API_KEY,
subscan: process.env.SUBSCAN_API_KEY,
};
// Demo keys (CG- prefix) ONLY work on api.coingecko.com — pro keys use pro-api.coingecko.com.
// Sending a demo key to the pro endpoint (or vice versa) returns 401.
const _cgKey = process.env.COINGECKO_KEY;
const _cgIsDemo = _cgKey && _cgKey.startsWith('CG-');
const CG_BASE = (_cgKey && !_cgIsDemo) ? 'https://pro-api.coingecko.com' : 'https://api.coingecko.com';
const cgHeaders = () => {
if (!_cgKey) return {};
return _cgIsDemo ? { 'x-cg-demo-api-key': _cgKey } : { 'x-cg-pro-api-key': _cgKey };
};
console.log(_cgKey ? `✅ CoinGecko API key loaded (${_cgIsDemo ? 'demo' : 'pro'} tier)` : '⚠️ No COINGECKO_KEY — free tier only');
const CMC_BASE = 'https://pro-api.coinmarketcap.com';
const cmcHeaders = () => {
if (!API_KEYS.coinmarketcap) return null;
return { accept: 'application/json', 'X-CMC_PRO_API_KEY': API_KEYS.coinmarketcap };
};
const cmcUsdQuote = (coin) => {
if (Array.isArray(coin?.quote)) {
return coin.quote.find(q => q?.symbol === 'USD' || q?.id === 2781) || coin.quote[0] || {};
}
return coin?.quote?.USD || {};
};
const cmcLogoUrl = (id) => id ? `https://s2.coinmarketcap.com/static/img/coins/64x64/${id}.png` : '';
const mapCmcCoinForChainLens = (coin, idx = 0) => {
const quote = cmcUsdQuote(coin);
const price = Number(quote.price) || 0;
return {
id: coin.slug || (coin.symbol || '').toLowerCase(),
symbol: (coin.symbol || '').toLowerCase(),
name: coin.name || coin.symbol || 'Unknown',
image: cmcLogoUrl(coin.id),
current_price: price,
market_cap: Number(quote.market_cap) || 0,
market_cap_rank: coin.cmc_rank || idx + 1,
fully_diluted_valuation: Number(quote.fully_diluted_market_cap) || 0,
total_volume: Number(quote.volume_24h) || 0,
high_24h: null,
low_24h: null,
price_change_24h: null,
price_change_percentage_24h: Number(quote.percent_change_24h) || 0,
market_cap_change_24h: null,
market_cap_change_percentage_24h: null,
circulating_supply: Number(coin.circulating_supply) || null,
total_supply: Number(coin.total_supply) || null,
max_supply: Number(coin.max_supply) || null,
ath: null,
ath_change_percentage: null,
ath_date: null,
atl: null,
atl_change_percentage: null,
atl_date: null,
roi: null,
last_updated: quote.last_updated || coin.last_updated || null,
sparkline_in_7d: null,
price_change_percentage_24h_in_currency: Number(quote.percent_change_24h) || 0,
source: 'CoinMarketCap',
};
};
const fetchCmcJson = async (path, params = {}, timeoutMs = 8000) => {
const headers = cmcHeaders();
if (!headers) throw new Error('COINMARKETCAP_API_KEY missing');
const url = new URL(`${CMC_BASE}${path}`);
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') url.searchParams.set(key, String(value));
});
const response = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
const json = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(`CoinMarketCap ${response.status}: ${json.status?.error_message || 'request failed'}`);
return json;
};
const fetchCmcListings = async (limit = 100) => {
const json = await fetchCmcJson('/v3/cryptocurrency/listings/latest', {
start: 1,
limit,
convert: 'USD',
sort: 'market_cap',
sort_dir: 'desc',
}, 10000);
const rows = Array.isArray(json.data) ? json.data : [];
if (rows.length === 0) throw new Error('CoinMarketCap empty listings');
return rows.map(mapCmcCoinForChainLens);
};
const fetchCmcQuote = async (query) => {
const normalized = String(query || '').trim();
if (!normalized) throw new Error('CoinMarketCap empty query');
const attempts = [];
if (/^[a-z0-9$@]{1,15}$/i.test(normalized)) {
attempts.push({ symbol: normalized.toUpperCase(), convert: 'USD', skip_invalid: true });
}
attempts.push({ slug: normalized.toLowerCase().replace(/\s+/g, '-'), convert: 'USD', skip_invalid: true });
let lastErr = null;
for (const params of attempts) {
try {
const json = await fetchCmcJson('/v3/cryptocurrency/quotes/latest', params, 8000);
const rows = (Array.isArray(json.data) ? json.data : Object.values(json.data || {})).flat();
const coin = rows.find(Boolean);
if (coin) return mapCmcCoinForChainLens(coin);
lastErr = new Error('CoinMarketCap no quote');
} catch (e) {
lastErr = e;
}
}
throw lastErr || new Error('CoinMarketCap no quote');
};
const fetchCmcChart = async (symbol, timeframeConfig) => {
const intervalByDays = {
1: '1h',
7: '4h',
30: '1d',
365: '7d',
max: '30d',
};
const countByDays = {
1: 24,
7: 42,
30: 30,
365: 53,
max: 120,
};
const daysKey = String(timeframeConfig.days);
const json = await fetchCmcJson('/v3/cryptocurrency/quotes/historical', {
symbol: String(symbol || '').toUpperCase(),
interval: intervalByDays[daysKey] || '4h',
count: countByDays[daysKey] || 42,
convert: 'USD',
skip_invalid: true,
}, 10000);
const container = json.data && (json.data[String(symbol).toUpperCase()] || Object.values(json.data)[0]);
const quotes = Array.isArray(container?.quotes) ? container.quotes : [];
const formattedPrices = quotes
.map(q => ({ time: Date.parse(q.timestamp), price: Number(q.quote?.USD?.price) }))
.filter(p => Number.isFinite(p.time) && p.price > 0)
.sort((a, b) => a.time - b.time);
if (formattedPrices.length < 2) throw new Error('CoinMarketCap empty chart');
return formattedPrices;
};
console.log(API_KEYS.coinmarketcap ? '✅ CoinMarketCap API key loaded' : '⚠️ No COINMARKETCAP_API_KEY — CMC fallback disabled');
// Binance endpoint rotation — if one host is throttled or down, the next is tried
const BINANCE_HOSTS = [
'https://api.binance.com',
'https://api-gcp.binance.com',
'https://api1.binance.com',
'https://api2.binance.com',
'https://api3.binance.com',
'https://api4.binance.com',
];
const fetchBinance = async (path, timeoutMs = 5000) => {
for (const host of BINANCE_HOSTS) {
try {
const r = await fetch(`${host}${path}`, { signal: AbortSignal.timeout(timeoutMs) });
if (r.ok) return r;
} catch {}
}
return null;
};
const APP_HUB_CHAINS = [
{ id: 'ethereum', label: 'Ethereum' },
{ id: 'base', label: 'Base' },
{ id: 'polygon', label: 'Polygon' },
{ id: 'avalanche', label: 'Avalanche' },
{ id: 'optimism', label: 'Optimism' },
{ id: 'arbitrum', label: 'Arbitrum' },
{ id: 'abstract', label: 'Abstract' },
{ id: 'blast', label: 'Blast' },
{ id: 'zora', label: 'Zora' },
{ id: 'apechain', label: 'Ape Chain' },
{ id: 'soneium', label: 'Soneium' },
{ id: 'ronin', label: 'Ronin' },
{ id: 'worldchain', label: 'World Chain' },
{ id: 'gnosis', label: 'Gnosis' },
{ id: 'hyperevm', label: 'HyperEVM' },
{ id: 'monad', label: 'Monad' },
{ id: 'solana', label: 'Solana' },
{ id: 'cardano', label: 'Cardano' }
];
const APP_HUB_CATEGORY_META = {
'Bridge / Interoperability': {
short: 'Bridge',
description: 'Move assets and messages across ecosystems.',
accent: 'cyan'
},
'DEX / Bridge Aggregator': {
short: 'DEX',
description: 'Find routes, swaps, and cross-chain liquidity.',
accent: 'emerald'
},
'Portfolio & Analytics': {
short: 'Analytics',
description: 'Track wallets, markets, positions, and onchain activity.',
accent: 'blue'
},
'NFT Marketplace': {
short: 'NFTs',
description: 'Discover, buy, sell, and analyze NFT collections.',
accent: 'amber'
}
};
const APP_HUB_APPS = [
{ name: 'Wormhole', category: 'Bridge / Interoperability', website: 'https://wormhole.com', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'gnosis', 'monad', 'solana', 'cardano'] },
{ name: 'LayerZero', category: 'Bridge / Interoperability', website: 'https://layerzero.network', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'abstract', 'blast', 'zora', 'apechain', 'soneium', 'ronin', 'worldchain', 'gnosis', 'monad', 'solana'] },
{ name: 'deBridge', category: 'Bridge / Interoperability', website: 'https://debridge.finance', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'solana'] },
{ name: 'Across Protocol', category: 'Bridge / Interoperability', website: 'https://across.to', chains: ['ethereum', 'base', 'optimism', 'arbitrum', 'blast', 'zora'] },
{ name: 'Stargate Finance', category: 'Bridge / Interoperability', website: 'https://stargate.finance', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast'] },
{ name: 'Jumper Exchange', category: 'DEX / Bridge Aggregator', website: 'https://jumper.exchange', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'gnosis', 'solana'] },
{ name: 'Pulsar Finance', category: 'Portfolio & Analytics', website: 'https://pulsar.finance', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'gnosis', 'solana', 'cardano'] },
{ name: 'CoinStats', category: 'Portfolio & Analytics', website: 'https://coinstats.app', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'gnosis', 'solana', 'cardano'] },
{ name: 'DeBank', category: 'Portfolio & Analytics', website: 'https://debank.com', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'zora', 'ronin', 'worldchain', 'gnosis'] },
{ name: 'Zapper', category: 'Portfolio & Analytics', website: 'https://zapper.xyz', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'zora', 'gnosis'] },
{ name: 'DefiLlama', category: 'Portfolio & Analytics', website: 'https://defillama.com', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'abstract', 'blast', 'zora', 'apechain', 'soneium', 'ronin', 'worldchain', 'gnosis', 'hyperevm', 'monad', 'solana', 'cardano'] },
{ name: 'DappRadar', category: 'Portfolio & Analytics', website: 'https://dappradar.com', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'zora', 'ronin', 'gnosis', 'solana', 'cardano'] },
{ name: 'Magic Eden', category: 'NFT Marketplace', website: 'https://magiceden.io', chains: ['ethereum', 'base', 'polygon', 'arbitrum', 'solana'] },
{ name: 'OpenSea', category: 'NFT Marketplace', website: 'https://opensea.io', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'zora', 'solana'] },
{ name: 'Element Market', category: 'NFT Marketplace', website: 'https://element.market', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'zora', 'solana'] },
{ name: '1inch Network', category: 'DEX / Bridge Aggregator', website: 'https://1inch.io', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'gnosis'] },
{ name: 'OpenOcean', category: 'DEX / Bridge Aggregator', website: 'https://openocean.finance', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'gnosis', 'solana'] },
{ name: 'Odos', category: 'DEX / Bridge Aggregator', website: 'https://odos.xyz', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'gnosis'] },
{ name: 'Matcha', category: 'DEX / Bridge Aggregator', website: 'https://matcha.xyz', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast'] },
{ name: 'Paraswap', category: 'DEX / Bridge Aggregator', website: 'https://paraswap.io', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum'] },
{ name: 'Celer Network', category: 'Bridge / Interoperability', website: 'https://celer.network', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'gnosis', 'solana'] },
{ name: 'Axelar', category: 'Bridge / Interoperability', website: 'https://axelar.network', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'gnosis'] },
{ name: 'Orbiter Finance', category: 'Bridge / Interoperability', website: 'https://orbiter.finance', chains: ['ethereum', 'base', 'polygon', 'optimism', 'arbitrum', 'blast', 'zora'] },
{ name: 'Symbiosis Finance', category: 'Bridge / Interoperability', website: 'https://symbiosis.finance', chains: ['ethereum', 'base', 'polygon', 'avalanche', 'optimism', 'arbitrum', 'blast', 'zora', 'ronin'] },
{ name: 'Owlto Finance', category: 'Bridge / Interoperability', website: 'https://owlto.finance', chains: ['ethereum', 'base', 'polygon', 'optimism', 'arbitrum', 'blast', 'zora'] }
];
const normalizeAppHubApp = (appRecord) => ({
...appRecord,
id: appRecord.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''),
chainCount: appRecord.chains.length,
coverage: Math.round((appRecord.chains.length / APP_HUB_CHAINS.length) * 100),
categoryMeta: APP_HUB_CATEGORY_META[appRecord.category] || {}
});
const getAppHubPayload = () => {
const apps = APP_HUB_APPS.map(normalizeAppHubApp);
const categories = Object.entries(APP_HUB_CATEGORY_META).map(([name, meta]) => ({
name,
...meta,
count: apps.filter(appRecord => appRecord.category === name).length
}));
const chainStats = APP_HUB_CHAINS.map(chain => ({
...chain,
count: apps.filter(appRecord => appRecord.chains.includes(chain.id)).length
}));
return {
updatedAt: '2026-06-05',
totalApps: apps.length,
totalChains: APP_HUB_CHAINS.length,
chains: APP_HUB_CHAINS,
categories,
chainStats,
apps
};
};
// --- Price Discovery Helper ---
// CoinGecko IDs for native tokens
const NATIVE_CG_IDS = {
ETH: 'ethereum', MATIC: 'matic-network', POL: 'matic-network',
AVAX: 'avalanche-2', RON: 'ronin', APE: 'apecoin',
MON: 'monad', SOL: 'solana', ADA: 'cardano', BNB: 'binancecoin',
XDAI: 'xdai', HYPE: 'hyperliquid', WLD: 'worldcoin-wld',
BTC: 'bitcoin', DOT: 'polkadot', TRX: 'tron', DOGE: 'dogecoin',
USDC: 'usd-coin'
};
// Simple price cache — 90s TTL
const _priceCache = {};
const _cGet = (k) => (_priceCache[k] && Date.now() - _priceCache[k].ts < 90000) ? _priceCache[k].v : null;
const _cSet = (k, v) => { _priceCache[k] = { v, ts: Date.now() }; return v; };
// Single CoinGecko fetch with cache
const fetchCoinGeckoPrice = async (cgId) => {
const hit = _cGet(cgId);
if (hit !== null) return hit;
try {
const r = await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${cgId}&vs_currencies=usd`);
const d = await r.json();
return _cSet(cgId, d[cgId]?.usd || 0);
} catch (e) { return _cSet(cgId, 0); }
};
// Fetch price for a native token by symbol
const fetchNativePrice = async (symbol) => {
const cgId = NATIVE_CG_IDS[symbol?.toUpperCase()];
return cgId ? fetchCoinGeckoPrice(cgId) : 0;
};
// DexScreener chain IDs
const DS_CHAIN = {
ethereum:'ethereum', base:'base', polygon:'polygon', abstract:'abstract',
monad:'monad', avalanche:'avalanche', optimism:'optimism', arbitrum:'arbitrum',
blast:'blast', zora:'zora', apechain:'ape', soneium:'soneium',
ronin:'ronin', worldchain:'worldchain', arc:'arc',
};
// DefiLlama chain slugs (free coins API — no key needed)
// https://coins.llama.fi/prices/current/chain:address
const LLAMA_CHAIN = {
ethereum:'ethereum', base:'base', polygon:'polygon', avalanche:'avax',
optimism:'optimism', arbitrum:'arbitrum', blast:'blast', zora:'zora',
abstract:'abstract', apechain:'apechain', soneium:'soneium', ronin:'ronin',
worldchain:'worldchain', gnosis:'xdai', hyperevm:'hyperliquid', monad:'monad',
arc:'arc', solana:'solana', cardano:'cardano',
};
// Single DefiLlama token price lookup — used as fallback when DexScreener returns 0
const fetchLlamaPrice = async (chainId, address) => {
const llamaChain = LLAMA_CHAIN[chainId];
if (!llamaChain || !address) return 0;
const key = `llama-${chainId}-${address}`;
const hit = _cGet(key);
if (hit !== null) return hit;
try {
const coin = `${llamaChain}:${address}`;
const r = await fetch(`https://coins.llama.fi/prices/current/${encodeURIComponent(coin)}`);
const d = await r.json();
const price = d?.coins?.[coin]?.price || 0;
if (price > 0) console.log(`🦙 DefiLlama price for ${coin}: $${price}`);
return _cSet(key, price);
} catch (e) { return _cSet(key, 0); }
};
// ERC20 price via DexScreener → DefiLlama fallback, with cache
const fetchUSDPrice = async (chainId, address) => {
if (!address || address === '0x0000000000000000000000000000000000000000') return 0;
const key = `ds-${chainId}-${address}`;
const hit = _cGet(key);
if (hit !== null) return hit;
try {
const dsChain = DS_CHAIN[chainId] || chainId;
const res = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${address}`);
const data = await res.json();
const pair = data.pairs?.find(p => p.chainId === dsChain) || data.pairs?.[0];
const dsPrice = pair ? parseFloat(pair.priceUsd) : 0;
if (dsPrice > 0) return _cSet(key, dsPrice);
// Fallback: DefiLlama Coins API
const llamaPrice = await fetchLlamaPrice(chainId, address);
return _cSet(key, llamaPrice);
} catch (e) {
// DexScreener failed — try Llama directly
const llamaPrice = await fetchLlamaPrice(chainId, address);
return _cSet(key, llamaPrice);
}
};
// Convert a USD value to native token equivalent, formatted to 4dp
const toNativePrice = (usdValue, nativeUsdPrice) =>
(nativeUsdPrice > 0 && usdValue > 0) ? (usdValue / nativeUsdPrice).toFixed(4) : '0.0000';
// Image cache — 24hr TTL (logos rarely change)
const _imageCache = {};
const fetchTokenImage = async (symbol) => {
if (!symbol) return '';
const key = symbol.toLowerCase();
if (_imageCache[key] !== undefined) return _imageCache[key];
try {
const r = await fetch(`https://api.coingecko.com/api/v3/search?query=${encodeURIComponent(symbol)}`);
if (!r.ok) { _imageCache[key] = ''; return ''; }
const d = await r.json();
const hit = d.coins?.find(c => c.symbol?.toLowerCase() === key) || d.coins?.[0];
const img = hit?.large || hit?.small || hit?.thumb || '';
_imageCache[key] = img;
return img;
} catch { _imageCache[key] = ''; return ''; }
};
// Fetch token logo by contract address — queries DexScreener, cached 24hr
const fetchTokenImageByAddress = async (dsChain, address) => {
if (!dsChain || !address) return '';
const key = `dex-${dsChain}-${address.toLowerCase()}`;
if (_imageCache[key] !== undefined) return _imageCache[key];
try {
const r = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${address}`);
if (!r.ok) { _imageCache[key] = ''; return ''; }
const d = await r.json();
// Prefer pair on the same chain, then any pair
const img = d.pairs?.find(p => p.chainId === dsChain)?.info?.imageUrl
|| d.pairs?.[0]?.info?.imageUrl || '';
_imageCache[key] = img;
return img;
} catch { _imageCache[key] = ''; return ''; }
};
// ══════════════════════════════════════════════════════════════════════════════
// AUTH & PROFILE ROUTES
// ══════════════════════════════════════════════════════════════════════════════
// The exact string a wallet signs to prove address ownership. Shared by
// /wallet-login and /wallet-session so the two can never drift apart, and
// mirrored byte-for-byte in the MagicMoney wallet (src/main/chainlens-auth.ts —
// `loginMessage`). Any change here reads as "signature mismatch" on the client
// with nothing pointing at why, so it is not a string to edit casually.
const loginMessage = (address, nonce) => `ChainLens login\nAddress: ${address}\nNonce: ${nonce}`;
// ── Step 1: Generate a nonce for wallet signing (public, no auth) ─────────────
app.post('/api/auth/nonce', (req, res) => {
const { address } = req.body;
if (!address) return res.status(400).json({ error: 'address required' });
const key = address.toLowerCase();
const nonce = crypto.randomBytes(32).toString('hex');
_authNonces[key] = { nonce, expires: Date.now() + 5 * 60 * 1000 };
res.json({ nonce });
});
// ── Step 2a: Login / link via wallet signature ────────────────────────────────
// If Authorization header present → links wallet to existing account
// If no header → creates/finds account keyed by wallet address
app.post('/api/auth/wallet-login', async (req, res) => {
const { chain, address, signature, key: cborKey, nonce } = req.body;
if (!chain || !address || !signature || !nonce)
return res.status(400).json({ error: 'chain, address, signature, nonce required' });
// Validate nonce
const addrKey = address.toLowerCase();
const stored = _authNonces[addrKey];
if (!stored || stored.nonce !== nonce || stored.expires < Date.now())
return res.status(400).json({ error: 'Invalid or expired nonce' });
delete _authNonces[addrKey]; // consume
const message = loginMessage(address, nonce);
// ── Verify signature ──────────────────────────────────────────────────────
// Fail CLOSED. These used to read `&& ethersVerify` / `&& nacl`, so a host
// where the module failed to load skipped verification entirely and still
// issued a 30-day JWT for any address the caller named. /wallet-session
// already 503s for the same reason.
if (chain === 'evm') {
if (!ethersVerify) return res.status(503).json({ error: 'Signature verification unavailable' });
try {
const recovered = ethersVerify(message, signature);
if (recovered.toLowerCase() !== address.toLowerCase())
return res.status(400).json({ error: 'EVM signature mismatch' });
} catch (e) { return res.status(400).json({ error: 'Invalid EVM signature' }); }
}
if (chain === 'solana') {
if (!nacl) return res.status(503).json({ error: 'Signature verification unavailable' });
try {
const msgBytes = Buffer.from(message);
const sigBytes = Buffer.from(signature, 'base64');
const pubBytes = base58Decode(address);
const valid = nacl.sign.detached.verify(msgBytes, sigBytes, pubBytes);
if (!valid) return res.status(400).json({ error: 'Solana signature mismatch' });
} catch (e) { return res.status(400).json({ error: 'Invalid Solana signature' }); }
}
// Cardano CIP-30 — signature is CBOR; basic address ownership check for now
// Full CIP-8 verification: add @emurgo/cardano-serialization-lib-nodejs
if (chain === 'cardano') {
if (!signature || !cborKey)
return res.status(400).json({ error: 'Cardano requires signature + key' });
// TODO: decode CBOR and verify with CSL for production hardening
console.log(`ℹ️ Cardano wallet ${address.substring(0, 20)}... linked (signature accepted)`);
}
// ── Determine if this is a link (existing session) or new login ───────────
const authHeader = req.headers.authorization?.replace('Bearer ', '');
let userId = null;
if (authHeader) {
try {
const claims = jwt.verify(authHeader, JWT_SECRET);
userId = claims.sub;
} catch (e) { /* token invalid — treat as new login */ }
}
if (supabase) {
if (userId) {
// Link wallet to existing account
await dbLinkWallet(userId, { chain, address });
// ── Auto-derive AGW address if this is an EVM wallet ──────────────────
if (chain === 'evm') {
const agwAddress = await deriveAGWAddress(address);
if (agwAddress && agwAddress !== address) {
await dbLinkWallet(userId, { chain: 'evm', address: agwAddress.toLowerCase(), watch_only: true });
console.log(`⚡ AGW watch-wallet auto-linked for user ${userId}`);
}
}
const profile = await dbGetUserById(userId);
return res.json({ success: true, profile });
} else {
// Create/find account by wallet address
const user = await dbUpsertUser({
provider: chain + '_wallet',
provider_id: address.toLowerCase(),
display_name: address.substring(0, 8) + '...' + address.slice(-4),
avatar_url: null, email: null
});
await dbLinkWallet(user.id, { chain, address });
// ── Auto-derive AGW address if this is an EVM wallet ──────────────────
if (chain === 'evm') {