-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.mjs
More file actions
2895 lines (2595 loc) · 119 KB
/
Copy pathserver.mjs
File metadata and controls
2895 lines (2595 loc) · 119 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
import 'dotenv/config';
import express from 'express';
import { fileURLToPath } from 'url';
import path from 'path';
import fs from 'fs';
import https from 'https';
import http from 'http';
import { spawn } from 'child_process';
import { tmpdir } from 'os';
import { mkdtempSync, writeFileSync, rmSync } from 'fs';
import { randomUUID, randomBytes, createHash } from 'crypto';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import { createRequire } from 'module';
import { Client, GatewayIntentBits, Events } from 'discord.js';
// node-pty ships as CJS; use createRequire for ESM compatibility
const require = createRequire(import.meta.url);
const pty = require('node-pty');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = parseInt(process.env.REPLIT_SERVER_PORT || '3001', 10);
app.use(express.json({ limit: '8mb' }));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
if (req.method === 'OPTIONS') return res.sendStatus(200);
next();
});
// ---------------------------------------------------------------------------
// Discord Activity — OAuth2 token exchange endpoint
// ---------------------------------------------------------------------------
app.post('/api/token', async (req, res) => {
try {
const clientId = process.env.VITE_DISCORD_CLIENT_ID;
const clientSecret = process.env.DISCORD_CLIENT_SECRET;
if (!clientId || !clientSecret) {
console.error('[Discord] Token exchange: VITE_DISCORD_CLIENT_ID or DISCORD_CLIENT_SECRET not set');
return res.status(500).json({ error: 'Discord OAuth2 credentials not configured on server' });
}
const body = new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
grant_type: 'authorization_code',
code: req.body.code,
redirect_uri: 'https://127.0.0.1',
});
const response = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
});
const data = await response.json();
if (!response.ok) {
console.error('[Discord] Token exchange error from Discord:', JSON.stringify(data));
return res.status(response.status).json({ error: data.error_description || data.error });
}
console.log('[Discord] Token exchange successful');
res.json({ access_token: data.access_token });
} catch (err) {
console.error('[Discord] Token exchange exception:', err.message);
res.status(500).json({ error: err.message });
}
});
// ---------------------------------------------------------------------------
// OAuth — userinfo + token refresh for "Login with Code Canvas" external apps
// ---------------------------------------------------------------------------
app.get('/api/oauth/userinfo', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or invalid Authorization header' });
}
const token = authHeader.slice(7);
const SUPABASE_URL = process.env.VITE_SUPABASE_URL;
const SUPABASE_ANON_KEY = process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
return res.status(500).json({ error: 'Supabase not configured on server' });
}
const resp = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
headers: { Authorization: `Bearer ${token}`, apikey: SUPABASE_ANON_KEY },
});
if (!resp.ok) {
return res.status(401).json({ error: 'Token invalid or expired' });
}
const userData = await resp.json();
const userId = userData.id;
if (!userId) {
return res.status(401).json({ error: 'Could not identify user from token' });
}
const profileResp = await fetch(`${SUPABASE_URL}/rest/v1/profiles?user_id=eq.${userId}&select=*`, {
headers: { Authorization: `Bearer ${token}`, apikey: SUPABASE_ANON_KEY, 'Content-Type': 'application/json' },
});
let profile = null;
if (profileResp.ok) {
const profiles = await profileResp.json();
profile = Array.isArray(profiles) && profiles.length > 0 ? profiles[0] : null;
}
res.json({
id: userId,
email: userData.email || null,
display_name: profile?.display_name || null,
avatar_url: profile?.avatar_url || null,
});
} catch (err) {
console.error('[OAuth] userinfo error:', err.message);
res.status(500).json({ error: 'Internal server error' });
}
});
app.post('/api/oauth/token/refresh', async (req, res) => {
try {
const { refresh_token } = req.body || {};
if (!refresh_token) {
return res.status(400).json({ error: 'refresh_token required' });
}
const SUPABASE_URL = process.env.VITE_SUPABASE_URL;
const SUPABASE_ANON_KEY = process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
return res.status(500).json({ error: 'Supabase not configured on server' });
}
const resp = await fetch(`${SUPABASE_URL}/auth/v1/token?grant_type=refresh_token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', apikey: SUPABASE_ANON_KEY },
body: JSON.stringify({ refresh_token }),
});
const data = await resp.json();
if (!resp.ok) {
return res.status(401).json({ error: data.error_description || data.error || 'Refresh failed' });
}
res.json({
access_token: data.access_token,
refresh_token: data.refresh_token,
expires_in: data.expires_in,
});
} catch (err) {
console.error('[OAuth] token refresh error:', err.message);
res.status(500).json({ error: 'Internal server error' });
}
});
// ---------------------------------------------------------------------------
// OAuth — create a Redactor proxy key for the external app
// ---------------------------------------------------------------------------
app.post('/api/oauth/redactor/proxy-keys', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or invalid Authorization header' });
}
const token = authHeader.slice(7);
const SUPABASE_URL = process.env.VITE_SUPABASE_URL;
const SUPABASE_ANON_KEY = process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
return res.status(500).json({ error: 'Supabase not configured on server' });
}
// Validate token and get user
const userResp = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
headers: { Authorization: `Bearer ${token}`, apikey: SUPABASE_ANON_KEY },
});
if (!userResp.ok) {
return res.status(401).json({ error: 'Token invalid or expired' });
}
const userData = await userResp.json();
const userId = userData.id;
if (!userId) return res.status(401).json({ error: 'Could not identify user from token' });
// Generate proxy key
const raw = randomBytes(32);
const randomStr = Array.from(raw).map((b) => b.toString(36).padStart(2, '0')).join('');
const fullKey = `lvp_live_${randomStr}`;
const prefix = fullKey.slice(0, 16);
const hash = createHash('sha256').update(fullKey).digest('hex');
const { name, allowed_providers, rate_limit_rpm, monthly_cap_usd, ip_allowlist, log_requests, redact_images, redact_videos, expires_at } = req.body || {};
// Insert via Supabase REST API (JWT auth passes user context for RLS)
const insertResp = await fetch(`${SUPABASE_URL}/rest/v1/redactor_proxy_keys`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
apikey: SUPABASE_ANON_KEY,
'Content-Type': 'application/json',
Prefer: 'return=representation',
},
body: JSON.stringify({
key_hash: hash,
key_prefix: prefix,
name: name || 'OAuth-generated key',
allowed_providers: allowed_providers || [],
rate_limit_rpm: rate_limit_rpm || null,
monthly_cap_usd: monthly_cap_usd || null,
ip_allowlist: ip_allowlist || [],
log_requests: log_requests !== undefined ? log_requests : true,
redact_images: redact_images !== undefined ? redact_images : true,
redact_videos: redact_videos !== undefined ? redact_videos : true,
expires_at: expires_at || null,
}),
});
if (!insertResp.ok) {
const errBody = await insertResp.text();
console.error('[OAuth] Failed to insert proxy key:', errBody);
return res.status(500).json({ error: 'Failed to create proxy key' });
}
const inserted = await insertResp.json();
const row = Array.isArray(inserted) ? inserted[0] : inserted;
res.status(201).json({
id: row.id,
name: row.name,
key: fullKey,
prefix: row.key_prefix,
allowed_providers: row.allowed_providers,
rate_limit_rpm: row.rate_limit_rpm,
monthly_cap_usd: row.monthly_cap_usd,
expires_at: row.expires_at,
created_at: row.created_at,
});
} catch (err) {
console.error('[OAuth] proxy key creation error:', err.message);
res.status(500).json({ error: 'Internal server error' });
}
});
// ---------------------------------------------------------------------------
// OAuth — list external app's Redactor proxy keys
// ---------------------------------------------------------------------------
app.get('/api/oauth/redactor/proxy-keys', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or invalid Authorization header' });
}
const token = authHeader.slice(7);
const SUPABASE_URL = process.env.VITE_SUPABASE_URL;
const SUPABASE_ANON_KEY = process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
return res.status(500).json({ error: 'Supabase not configured on server' });
}
const userResp = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
headers: { Authorization: `Bearer ${token}`, apikey: SUPABASE_ANON_KEY },
});
if (!userResp.ok) return res.status(401).json({ error: 'Token invalid or expired' });
const userData = await userResp.json();
if (!userData.id) return res.status(401).json({ error: 'Could not identify user from token' });
const keysResp = await fetch(`${SUPABASE_URL}/rest/v1/redactor_proxy_keys?order=created_at.desc`, {
headers: {
Authorization: `Bearer ${token}`,
apikey: SUPABASE_ANON_KEY,
'Content-Type': 'application/json',
},
});
if (!keysResp.ok) {
return res.status(500).json({ error: 'Failed to fetch proxy keys' });
}
const keys = await keysResp.json();
res.json(Array.isArray(keys) ? keys : []);
} catch (err) {
console.error('[OAuth] list proxy keys error:', err.message);
res.status(500).json({ error: 'Internal server error' });
}
});
// ---------------------------------------------------------------------------
// OAuth — revoke a Redactor proxy key
// ---------------------------------------------------------------------------
app.post('/api/oauth/redactor/proxy-keys/:id/revoke', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or invalid Authorization header' });
}
const token = authHeader.slice(7);
const SUPABASE_URL = process.env.VITE_SUPABASE_URL;
const SUPABASE_ANON_KEY = process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
return res.status(500).json({ error: 'Supabase not configured on server' });
}
const userResp = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
headers: { Authorization: `Bearer ${token}`, apikey: SUPABASE_ANON_KEY },
});
if (!userResp.ok) return res.status(401).json({ error: 'Token invalid or expired' });
const userData = await userResp.json();
if (!userData.id) return res.status(401).json({ error: 'Could not identify user from token' });
const { id } = req.params;
const updateResp = await fetch(`${SUPABASE_URL}/rest/v1/redactor_proxy_keys?id=eq.${id}`, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${token}`,
apikey: SUPABASE_ANON_KEY,
'Content-Type': 'application/json',
Prefer: 'return=representation',
},
body: JSON.stringify({ revoked_at: new Date().toISOString() }),
});
if (!updateResp.ok) {
return res.status(500).json({ error: 'Failed to revoke proxy key' });
}
res.json({ ok: true });
} catch (err) {
console.error('[OAuth] revoke proxy key error:', err.message);
res.status(500).json({ error: 'Internal server error' });
}
});
// ---------------------------------------------------------------------------
// OAuth — AI chat via the user's configured AI providers
// ---------------------------------------------------------------------------
app.post('/api/oauth/ai/chat', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or invalid Authorization header' });
}
const token = authHeader.slice(7);
const SUPABASE_URL = process.env.VITE_SUPABASE_URL;
const SUPABASE_ANON_KEY = process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
return res.status(500).json({ error: 'Supabase not configured on server' });
}
const userResp = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
headers: { Authorization: `Bearer ${token}`, apikey: SUPABASE_ANON_KEY },
});
if (!userResp.ok) return res.status(401).json({ error: 'Token invalid or expired' });
const userData = await userResp.json();
const userId = userData.id;
if (!userId) return res.status(401).json({ error: 'Could not identify user from token' });
const { model, messages, temperature, max_tokens, provider: requestedProvider } = req.body || {};
if (!messages || !Array.isArray(messages) || messages.length === 0) {
return res.status(400).json({ error: 'messages array is required' });
}
// Look up user's API keys from server file store
const userKeys = _aiKeys[userId] || {};
// Also check Supabase user_api_keys table
let supabaseKeys = [];
try {
const keysResp = await fetch(`${SUPABASE_URL}/rest/v1/user_api_keys?user_id=eq.${userId}&select=provider,api_key,base_url`, {
headers: { Authorization: `Bearer ${token}`, apikey: SUPABASE_ANON_KEY, 'Content-Type': 'application/json' },
});
if (keysResp.ok) {
supabaseKeys = await keysResp.json();
}
} catch { /* fallback to server store only */ }
for (const row of supabaseKeys) {
if (!userKeys[row.provider]) {
userKeys[row.provider] = { api_key: row.api_key, base_url: row.base_url || '' };
}
}
// Find the provider to use
let provider = requestedProvider || null;
let keyData = provider ? userKeys[provider] : null;
if (!provider || !keyData) {
// Auto-select first available provider
for (const p of Object.keys(BYOK_PROVIDERS)) {
if (p === 'openai-compatible') continue;
if (userKeys[p]) { provider = p; keyData = userKeys[p]; break; }
}
}
if (!provider || !keyData || !keyData.api_key) {
return res.status(503).json({ error: 'No AI API key configured for this user. They need to add one in their Code Canvas settings.' });
}
const isOpenAICompatible = provider === 'openai-compatible';
const cfg = isOpenAICompatible
? { url: keyData.base_url || '', authHeader: 'Bearer' }
: BYOK_PROVIDERS[provider];
if (!cfg || !cfg.url) {
return res.status(400).json({ error: `Unsupported provider: ${provider}` });
}
const effectiveModel = model || BYOK_DEFAULT_MODELS[provider] || 'gpt-4o';
const body = {
model: effectiveModel,
messages,
...(temperature !== undefined ? { temperature } : {}),
...(max_tokens !== undefined ? { max_tokens } : {}),
};
const headers = { 'Content-Type': 'application/json' };
if (cfg.authHeader === 'x-api-key') {
headers['x-api-key'] = keyData.api_key;
if (provider === 'anthropic') headers['anthropic-version'] = '2023-06-01';
} else {
headers['Authorization'] = `Bearer ${keyData.api_key}`;
}
const apiUrl = isOpenAICompatible
? `${cfg.url.replace(/\/$/, '')}/chat/completions`
: cfg.url;
const apiResp = await fetch(apiUrl, {
method: 'POST',
headers,
body: JSON.stringify(body),
});
const data = await apiResp.json();
if (!apiResp.ok) {
const errMsg = data?.error?.message || data?.error || `Provider returned ${apiResp.status}`;
return res.status(502).json({ error: errMsg, provider });
}
res.json(data);
} catch (err) {
console.error('[OAuth] AI chat error:', err.message);
res.status(500).json({ error: 'Internal server error' });
}
});
// ---------------------------------------------------------------------------
// OAuth — list the user's configured AI providers (no key values)
// ---------------------------------------------------------------------------
app.get('/api/oauth/ai/providers', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or invalid Authorization header' });
}
const token = authHeader.slice(7);
const SUPABASE_URL = process.env.VITE_SUPABASE_URL;
const SUPABASE_ANON_KEY = process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
return res.status(500).json({ error: 'Supabase not configured on server' });
}
const userResp = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
headers: { Authorization: `Bearer ${token}`, apikey: SUPABASE_ANON_KEY },
});
if (!userResp.ok) return res.status(401).json({ error: 'Token invalid or expired' });
const userData = await userResp.json();
const userId = userData.id;
if (!userId) return res.status(401).json({ error: 'Could not identify user from token' });
// Gather keys from both stores
const serverKeys = Object.keys(_aiKeys[userId] || {});
let supabaseKeys = [];
try {
const keysResp = await fetch(`${SUPABASE_URL}/rest/v1/user_api_keys?user_id=eq.${userId}&select=provider,base_url`, {
headers: { Authorization: `Bearer ${token}`, apikey: SUPABASE_ANON_KEY, 'Content-Type': 'application/json' },
});
if (keysResp.ok) {
supabaseKeys = await keysResp.json();
}
} catch { /* ignore */ }
const providerSet = new Set([...serverKeys, ...supabaseKeys.map((k) => k.provider)]);
const providers = Array.from(providerSet)
.filter((p) => p && p !== 'openai-compatible')
.sort();
res.json({ providers });
} catch (err) {
console.error('[OAuth] list providers error:', err.message);
res.status(500).json({ error: 'Internal server error' });
}
});
// ---------------------------------------------------------------------------
// Discord bot — link Discord user to authenticated web user
// ---------------------------------------------------------------------------
app.post('/api/discord/link', (req, res) => {
try {
const { code } = req.body || {};
const userId = req.headers['x-user-id'];
if (!code || !userId) {
return res.status(400).json({ error: 'Missing code or user id' });
}
let matchedDiscordId = null;
for (const [discordUserId, link] of Object.entries(_discordLinks)) {
if (link.authCode === code && !link.userId && link.authCodeExpiresAt > Date.now()) {
matchedDiscordId = discordUserId;
break;
}
}
if (!matchedDiscordId) {
return res.status(400).json({ error: 'Invalid or expired code. DM the bot again for a new code.' });
}
_discordLinks[matchedDiscordId].userId = userId;
_discordLinks[matchedDiscordId].linkedAt = new Date().toISOString();
delete _discordLinks[matchedDiscordId].authCode;
delete _discordLinks[matchedDiscordId].authCodeExpiresAt;
saveDiscordLinks();
console.log(`[Discord Bot] Linked Discord user ${matchedDiscordId} to Code Canvas user ${userId}`);
res.json({ ok: true, discordUserId: matchedDiscordId });
} catch (err) {
console.error('[Discord Bot] Link error:', err.message);
res.status(500).json({ error: err.message });
}
});
app.get('/api/discord/link-status', (req, res) => {
try {
const userId = req.headers['x-user-id'];
if (!userId) return res.status(400).json({ error: 'Missing user id' });
const linked = Object.entries(_discordLinks)
.filter(([, link]) => link.userId === userId)
.map(([discordUserId, link]) => ({
discordUserId,
discordUsername: link.discordUsername || null,
linkedAt: link.linkedAt,
}));
res.json({ linked });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ---------------------------------------------------------------------------
// Supabase proxy — allows Supabase API calls from within Discord's CSP-restricted iframe
// ---------------------------------------------------------------------------
function proxySupabase(targetUrl, req, res) {
const parsedUrl = new URL(targetUrl);
const protocol = parsedUrl.protocol === 'https:' ? https : http;
const port = parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80);
const options = {
method: req.method,
headers: { ...req.headers },
hostname: parsedUrl.hostname,
path: parsedUrl.pathname + parsedUrl.search,
port,
};
delete options.headers.host;
delete options.headers.connection;
delete options.headers.referer;
const proxyReq = protocol.request(options, (proxyRes) => {
const chunks = [];
proxyRes.on('data', (chunk) => chunks.push(chunk));
proxyRes.on('end', () => {
const body = Buffer.concat(chunks);
if (!res.headersSent) {
res.writeHead(proxyRes.statusCode, { ...proxyRes.headers, 'access-control-allow-origin': '*' });
}
res.end(body);
});
});
proxyReq.on('error', (err) => {
if (!res.headersSent) res.status(502).json({ error: err.message });
});
if (req.method === 'GET' || req.method === 'HEAD') {
proxyReq.end();
} else if (req.body && typeof req.body === 'object') {
const bodyStr = JSON.stringify(req.body);
proxyReq.setHeader('content-length', Buffer.byteLength(bodyStr));
proxyReq.end(bodyStr);
} else {
req.pipe(proxyReq, { end: true });
}
}
// Catch-all for /api/supabase/* — proxies to the real Supabase instance
app.all('/api/supabase/{*path}', (req, res) => {
const supabaseUrl = process.env.VITE_SUPABASE_URL;
if (!supabaseUrl) return res.status(500).json({ error: 'VITE_SUPABASE_URL not configured' });
const tail = Array.isArray(req.params.path) ? req.params.path.join('/') : req.params.path;
const target = `${supabaseUrl}/${tail}`;
proxySupabase(target, req, res);
});
// Redactor proxy — forwards /redactor/public/v1/* to the Supabase redactor-proxy edge function
app.all('/redactor/public/v1/{*path}', (req, res) => {
const supabaseUrl = process.env.VITE_SUPABASE_URL;
if (!supabaseUrl) return res.status(500).json({ error: 'VITE_SUPABASE_URL not configured' });
const tail = Array.isArray(req.params.path) ? req.params.path.join('/') : req.params.path;
const target = `${supabaseUrl}/functions/v1/redactor-proxy/v1/${tail}`;
proxySupabase(target, req, res);
});
// ---------------------------------------------------------------------------
// Model Proxy — allows downloading models from HuggingFace/CDNs via our server
// to bypass strict client-side firewalls or VPNs.
// ---------------------------------------------------------------------------
function proxyRequest(targetUrl, req, res, redirects = 0) {
if (redirects > 10) {
return res.status(502).send('Too many redirects');
}
// console.log(`[Proxy] ${req.method} ${targetUrl} (redirects: ${redirects})`);
const parsedUrl = new URL(targetUrl);
const options = {
method: req.method,
headers: { ...req.headers },
hostname: parsedUrl.hostname,
path: parsedUrl.pathname + parsedUrl.search,
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
};
// Strip headers that should not be forwarded
delete options.headers.host;
delete options.headers.connection;
delete options.headers.referer;
delete options.headers['content-length'];
delete options.headers.cookie;
delete options.headers.authorization;
delete options.headers['set-cookie'];
// Hugging Face can require a User-Agent and now requires auth for all downloads
options.headers['user-agent'] = 'CanvasIDE/1.0';
if (process.env.HF_TOKEN) {
options.headers['Authorization'] = `Bearer ${process.env.HF_TOKEN}`;
}
const protocol = parsedUrl.protocol === 'https:' ? https : http;
const proxyReq = protocol.request(options, (proxyRes) => {
// Handle redirects (HuggingFace often redirects to S3)
if (proxyRes.statusCode >= 300 && proxyRes.statusCode < 400 && proxyRes.headers.location) {
let nextUrl = proxyRes.headers.location;
if (!nextUrl.startsWith('http')) {
nextUrl = new URL(nextUrl, targetUrl).href;
}
return proxyRequest(nextUrl, req, res, redirects + 1);
}
// Forward the response
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
proxyReq.on('error', (err) => {
console.error(`Proxy error for ${targetUrl}:`, err.message);
if (!res.headersSent) {
res.status(502).json({ error: 'Proxy failed to reach target', message: err.message, target: targetUrl });
}
});
if (req.method === 'GET') {
proxyReq.end();
} else {
req.pipe(proxyReq, { end: true });
}
}
app.get(/^\/api\/proxy\/hf\/(.*)/, (req, res) => {
const targetUrl = `https://huggingface.co/${req.params[0]}`;
proxyRequest(targetUrl, req, res);
});
app.get(/^\/api\/proxy\/jsdelivr\/(.*)/, (req, res) => {
const targetUrl = `https://cdn.jsdelivr.net/${req.params[0]}`;
proxyRequest(targetUrl, req, res);
});
app.get(/^\/api\/proxy\/unpkg\/(.*)/, (req, res) => {
const targetUrl = `https://unpkg.com/${req.params[0]}`;
proxyRequest(targetUrl, req, res);
});
// Backward/hosted compatibility aliases.
// Some deployments only expose /api/replit/* routes to the browser,
// so mirror the model proxy endpoints there as well.
app.get(/^\/api\/replit\/proxy\/hf\/(.*)/, (req, res) => {
const targetUrl = `https://huggingface.co/${req.params[0]}`;
proxyRequest(targetUrl, req, res);
});
app.get(/^\/api\/replit\/proxy\/jsdelivr\/(.*)/, (req, res) => {
const targetUrl = `https://cdn.jsdelivr.net/${req.params[0]}`;
proxyRequest(targetUrl, req, res);
});
app.get(/^\/api\/replit\/proxy\/unpkg\/(.*)/, (req, res) => {
const targetUrl = `https://unpkg.com/${req.params[0]}`;
proxyRequest(targetUrl, req, res);
});
// ---------------------------------------------------------------------------
// AI proxy — self-contained, calls AI provider APIs directly from the server
// so no Supabase session is needed. BYOK keys are stored per-user in memory
// and on disk (aikeys.json) so they survive server restarts.
// ---------------------------------------------------------------------------
const AI_KEYS_FILE = path.join(__dirname, 'aikeys.json');
// { [userId]: { [provider]: apiKey } }
let _aiKeys = {};
try {
if (fs.existsSync(AI_KEYS_FILE)) {
_aiKeys = JSON.parse(fs.readFileSync(AI_KEYS_FILE, 'utf8'));
// Migrate old format to new object format
for (const uid of Object.keys(_aiKeys)) {
for (const provider of Object.keys(_aiKeys[uid])) {
if (typeof _aiKeys[uid][provider] === 'string') {
_aiKeys[uid][provider] = { api_key: _aiKeys[uid][provider], base_url: '' };
}
}
}
}
} catch { _aiKeys = {}; }
function saveAiKeys() {
try { fs.writeFileSync(AI_KEYS_FILE, JSON.stringify(_aiKeys)); } catch {}
}
// MCP server local storage — mirrors aikeys approach so no Supabase needed.
// { [userId]: MCPServer[] }
const MCP_FILE = path.join(__dirname, 'mcpservers.json');
let _mcpServers = {};
try {
if (fs.existsSync(MCP_FILE)) _mcpServers = JSON.parse(fs.readFileSync(MCP_FILE, 'utf8'));
} catch { _mcpServers = {}; }
function saveMcpServers() {
try { fs.writeFileSync(MCP_FILE, JSON.stringify(_mcpServers)); } catch {}
}
// Agent skills local storage — persists custom AI instructions per user.
// { [userId]: AgentSkill[] }
const SKILLS_FILE = path.join(__dirname, 'agentskills.json');
let _agentSkills = {};
try {
if (fs.existsSync(SKILLS_FILE)) _agentSkills = JSON.parse(fs.readFileSync(SKILLS_FILE, 'utf8'));
} catch { _agentSkills = {}; }
function saveAgentSkills() {
try { fs.writeFileSync(SKILLS_FILE, JSON.stringify(_agentSkills)); } catch {}
}
// ---------------------------------------------------------------------------
// Discord link storage — maps Discord user IDs to Supabase user IDs
// ---------------------------------------------------------------------------
const DISCORD_LINKS_FILE = path.join(__dirname, 'discord-links.json');
let _discordLinks = {};
try {
if (fs.existsSync(DISCORD_LINKS_FILE)) _discordLinks = JSON.parse(fs.readFileSync(DISCORD_LINKS_FILE, 'utf8'));
} catch { _discordLinks = {}; }
function saveDiscordLinks() {
try { fs.writeFileSync(DISCORD_LINKS_FILE, JSON.stringify(_discordLinks)); } catch {}
}
// ---------------------------------------------------------------------------
// Discord chat history — per-user conversation state for DM AI chats
// ---------------------------------------------------------------------------
const DISCORD_CHATS_FILE = path.join(__dirname, 'discord-chats.json');
let _discordChats = {};
try {
if (fs.existsSync(DISCORD_CHATS_FILE)) _discordChats = JSON.parse(fs.readFileSync(DISCORD_CHATS_FILE, 'utf8'));
} catch { _discordChats = {}; }
function saveDiscordChats() {
try { fs.writeFileSync(DISCORD_CHATS_FILE, JSON.stringify(_discordChats)); } catch {}
}
function getReplitUserId(req) {
return req.headers['x-replit-user-id'] || null;
}
// Provider endpoint configs (mirrors the edge function)
const BYOK_PROVIDERS = {
openai: { url: 'https://api.openai.com/v1/chat/completions', authHeader: 'Bearer' },
anthropic: { url: 'https://api.anthropic.com/v1/messages', authHeader: 'x-api-key' },
gemini: { url: 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions', authHeader: 'Bearer' },
perplexity: { url: 'https://api.perplexity.ai/chat/completions', authHeader: 'Bearer' },
deepseek: { url: 'https://api.deepseek.com/v1/chat/completions', authHeader: 'Bearer' },
xai: { url: 'https://api.x.ai/v1/chat/completions', authHeader: 'Bearer' },
cohere: { url: 'https://api.cohere.com/v2/chat', authHeader: 'Bearer' },
openrouter: { url: 'https://openrouter.ai/api/v1/chat/completions', authHeader: 'Bearer' },
pollinations:{ url: 'https://gen.pollinations.ai/v1/chat/completions', authHeader: 'Bearer' },
github: { url: 'https://models.inference.ai.azure.com/chat/completions', authHeader: 'Bearer' },
groq: { url: 'https://api.groq.com/openai/v1/chat/completions', authHeader: 'Bearer' },
'openai-compatible': { url: '', authHeader: 'Bearer' },
};
const BYOK_DEFAULT_MODELS = {
openai: 'gpt-4o', anthropic: 'claude-3-5-sonnet-latest', gemini: 'gemini-2.5-flash',
perplexity: 'sonar', deepseek: 'deepseek-chat', xai: 'grok-3-fast',
cohere: 'command-r-plus', openrouter: 'openai/gpt-4o', pollinations: 'openai', github: 'gpt-4o',
groq: 'llama-3.3-70b-versatile',
'openai-compatible': 'custom-model',
};
// BYOK key management endpoints
app.get('/api/replit/ai/keys', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
const userKeys = _aiKeys[uid] || {};
const sanitized = Object.keys(userKeys).map(provider => ({
id: `${uid}-${provider}`, provider, api_key: userKeys[provider].api_key,
base_url: userKeys[provider].base_url || null,
created_at: new Date().toISOString(), updated_at: new Date().toISOString(), user_id: uid,
}));
res.json(sanitized);
});
app.put('/api/replit/ai/keys', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
const { provider, api_key, base_url } = req.body || {};
if (!provider || !api_key) return res.status(400).json({ error: 'provider and api_key required' });
if (!_aiKeys[uid]) _aiKeys[uid] = {};
_aiKeys[uid][provider] = { api_key, base_url: base_url || '' };
saveAiKeys();
res.json({ ok: true });
});
app.delete('/api/replit/ai/keys', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
const { provider } = req.query;
if (!provider) return res.status(400).json({ error: 'provider required' });
if (_aiKeys[uid]) { delete _aiKeys[uid][provider]; saveAiKeys(); }
res.json({ ok: true });
});
// ---------------------------------------------------------------------------
// MCP server CRUD endpoints
// ---------------------------------------------------------------------------
app.get('/api/replit/ai/mcp-servers', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
res.json(_mcpServers[uid] || []);
});
app.post('/api/replit/ai/mcp-servers', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
const { name, url, description, api_key } = req.body || {};
if (!name || !url) return res.status(400).json({ error: 'name and url required' });
if (!_mcpServers[uid]) _mcpServers[uid] = [];
const now = new Date().toISOString();
const server = { id: randomUUID(), name, url, description: description || null, api_key: api_key || null, is_enabled: true, created_at: now, updated_at: now };
_mcpServers[uid].unshift(server);
saveMcpServers();
res.json(server);
});
app.patch('/api/replit/ai/mcp-servers/:id', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
const { id } = req.params;
const updates = req.body || {};
if (!_mcpServers[uid]) return res.status(404).json({ error: 'Not found' });
_mcpServers[uid] = _mcpServers[uid].map(s =>
s.id === id ? { ...s, ...updates, id, updated_at: new Date().toISOString() } : s
);
saveMcpServers();
res.json({ ok: true });
});
app.delete('/api/replit/ai/mcp-servers/:id', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
const { id } = req.params;
if (_mcpServers[uid]) _mcpServers[uid] = _mcpServers[uid].filter(s => s.id !== id);
saveMcpServers();
res.json({ ok: true });
});
// ---------------------------------------------------------------------------
// Agent skills CRUD endpoints
// ---------------------------------------------------------------------------
app.get('/api/replit/ai/skills', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
res.json(_agentSkills[uid] || []);
});
app.post('/api/replit/ai/skills', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
const { name, instruction, description, icon } = req.body || {};
if (!name || !instruction) return res.status(400).json({ error: 'name and instruction required' });
if (!_agentSkills[uid]) _agentSkills[uid] = [];
const now = new Date().toISOString();
const skill = { id: randomUUID(), name, instruction, description: description || null, icon: icon || 'sparkles', is_enabled: true, created_at: now, updated_at: now };
_agentSkills[uid].unshift(skill);
saveAgentSkills();
res.json(skill);
});
app.patch('/api/replit/ai/skills/:id', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
const { id } = req.params;
const updates = req.body || {};
if (!_agentSkills[uid]) return res.status(404).json({ error: 'Not found' });
_agentSkills[uid] = _agentSkills[uid].map(s =>
s.id === id ? { ...s, ...updates, id, updated_at: new Date().toISOString() } : s
);
saveAgentSkills();
res.json({ ok: true });
});
app.delete('/api/replit/ai/skills/:id', (req, res) => {
const uid = getReplitUserId(req);
if (!uid) return res.status(401).json({ error: 'Not authenticated' });
const { id } = req.params;
if (_agentSkills[uid]) _agentSkills[uid] = _agentSkills[uid].filter(s => s.id !== id);
saveAgentSkills();
res.json({ ok: true });
});
// ---------------------------------------------------------------------------
// Skills library — VoltAgent/awesome-agent-skills (public GitHub, no API key)
// ---------------------------------------------------------------------------
const AGENT_SKILLS_README_URL = 'https://raw.githubusercontent.com/VoltAgent/awesome-agent-skills/main/README.md';
// Strip common prefix from section headers to get a clean author/category name
function cleanCategoryHeader(raw) {
return raw
.replace(/<[^>]+>/g, '') // remove HTML tags
.replace(/^(Official\s+|Skills\s+by\s+|Skill\s+by\s+|Security\s+Skills\s+by\s+|Marketing\s+Skills\s+by\s+|Product\s+Manager\s+Skills\s+by\s+|Product\s+Management\s+Skills\s+by\s+|Advertising\s+Skills\s+by\s+)/i, '')
.replace(/\s+Team$/i, '')
.replace(/\s*❤️.*$/, '')
.trim();
}
// Extract the org/author from a skill id like "anthropics/docx" → "Anthropic"
function parseAgentSkillsReadme(md) {
const skills = [];
const lines = md.split('\n');
// Sections to skip entirely
const SKIP_SECTIONS = new Set([
'table of contents', 'sponsors', 'official skills by',
'skill quality standards', 'contributing', 'community skills',
'awesome agent skills',
]);
let currentCategory = 'Community';
for (const line of lines) {
// <summary><h3>Official Claude Skills</h3></summary> OR ### Skills by VoltAgent
const headerMatch =
line.match(/^\s*#{2,4}\s+(.+)/) ||
line.match(/<summary[^>]*><h[0-9][^>]*>([^<]+)<\/h[0-9]><\/summary>/i);
if (headerMatch) {
const raw = cleanCategoryHeader(headerMatch[1]);
if (raw && !SKIP_SECTIONS.has(raw.toLowerCase())) {
currentCategory = raw;
}
continue;
}
// Skill entry: - **[org/name](url)** - Description
const skillMatch = line.match(/^\s*[-*]\s+\*\*\[([^\]]+)\]\(([^)]+)\)\*\*\s*(?:\\?[-–]|[-–])\s*(.+)/);
if (skillMatch) {
const id = skillMatch[1].trim(); // e.g. "anthropics/docx"
const url = skillMatch[2].trim();
const description = skillMatch[3].replace(/\\$/, '').trim();
// Derive human-readable name: "anthropics/docx" → "docx" (keep id for uniqueness)
const nameParts = id.split('/');
const shortName = nameParts[nameParts.length - 1]
.replace(/-/g, ' ')
.replace(/\b\w/g, c => c.toUpperCase());
const author = currentCategory;
skills.push({
id,
name: shortName,
fullName: id,
description,
url,
category: currentCategory,
author,
stars: 0,
instruction: null,