Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
10866 lines (9715 loc) · 478 KB
/
Copy pathserver.ts
File metadata and controls
10866 lines (9715 loc) · 478 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 express from 'express';
import path from 'path';
import fs from 'fs';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
import { createServer as createViteServer } from 'vite';
const currentDir = typeof __dirname !== 'undefined' ? __dirname : process.cwd();
import { GoogleGenAI, Type, ThinkingLevel } from '@google/genai';
import nodemailer from 'nodemailer';
import * as cheerio from 'cheerio';
import { exec } from 'child_process';
import { createClient } from '@supabase/supabase-js';
import { generateMockStitchResponse } from './src/lib/mockBlueprints';
interface VectorItem {
id: string;
text: string;
embedding: number[];
source: string;
}
const vectorStore: VectorItem[] = [];
function cosineSimilarity(A: number[], B: number[]) {
let dotproduct = 0;
let mA = 0;
let mB = 0;
for(let i = 0; i < A.length; i++){
dotproduct += (A[i] * B[i]);
mA += (A[i]*A[i]);
mB += (B[i]*B[i]);
}
mA = Math.sqrt(mA);
mB = Math.sqrt(mB);
return (dotproduct)/((mA)*(mB));
}
function getAllFiles(dirPath: string, arrayOfFiles: string[] = []): string[] {
try {
const files = fs.readdirSync(dirPath);
for (const file of files) {
if (file === 'node_modules' || file === 'dist' || file === '.git' || file === '.next' || file === '.aistudio') {
continue;
}
const fullPath = path.join(dirPath, file);
if (fs.statSync(fullPath).isDirectory()) {
getAllFiles(fullPath, arrayOfFiles);
} else {
arrayOfFiles.push(path.relative(process.cwd(), fullPath));
}
}
} catch (err) {
console.error("Error walking directory:", err);
}
return arrayOfFiles;
}
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
// CORS middleware for seamless API access and preflight OPTIONS handling
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-gemini-api-key');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
// Health check endpoint for desktop & container readiness verification
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// Local Vendor Assets for Design Studio Sandbox (Zero-latency offline preview)
app.get('/api/vendor/babel.min.js', (req, res) => {
const babelPath = path.join(process.cwd(), 'node_modules/@babel/standalone/babel.min.js');
if (fs.existsSync(babelPath)) {
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'public, max-age=86400');
return res.sendFile(babelPath);
}
return res.status(404).send('// Babel standalone not found locally');
});
app.get('/api/vendor/lucide-react.min.js', (req, res) => {
const lucidePath = path.join(process.cwd(), 'node_modules/lucide-react/dist/umd/lucide-react.min.js');
if (fs.existsSync(lucidePath)) {
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'public, max-age=86400');
return res.sendFile(lucidePath);
}
return res.status(404).send('// Lucide React UMD not found locally');
});
app.get('/api/vendor/react.min.js', (req, res) => {
const reactPath = path.join(process.cwd(), 'public/vendor/react.production.min.js');
if (fs.existsSync(reactPath)) {
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'public, max-age=86400');
return res.sendFile(reactPath);
}
return res.status(404).send('// Local React UMD not found');
});
app.get('/api/vendor/react-dom.min.js', (req, res) => {
const reactDomPath = path.join(process.cwd(), 'public/vendor/react-dom.production.min.js');
if (fs.existsSync(reactDomPath)) {
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'public, max-age=86400');
return res.sendFile(reactDomPath);
}
return res.status(404).send('// Local ReactDOM UMD not found');
});
app.get('/api/vendor/status', (req, res) => {
const babelExists = fs.existsSync(path.join(process.cwd(), 'node_modules/@babel/standalone/babel.min.js'));
const lucideExists = fs.existsSync(path.join(process.cwd(), 'node_modules/lucide-react/dist/umd/lucide-react.min.js'));
const reactExists = fs.existsSync(path.join(process.cwd(), 'public/vendor/react.production.min.js'));
const reactDomExists = fs.existsSync(path.join(process.cwd(), 'public/vendor/react-dom.production.min.js'));
res.json({
status: 'ok',
vendorDependencies: {
babel: { localAvailable: babelExists, endpoint: '/api/vendor/babel.min.js' },
lucide: { localAvailable: lucideExists, endpoint: '/api/vendor/lucide-react.min.js' },
react: { localAvailable: reactExists, endpoint: '/api/vendor/react.min.js' },
reactDom: { localAvailable: reactDomExists, endpoint: '/api/vendor/react-dom.min.js' },
reactCDN: 'https://cdn.jsdelivr.net/npm/react@18/umd/react.production.min.js',
reactDomCDN: 'https://cdn.jsdelivr.net/npm/react-dom@18/umd/react-dom.production.min.js',
tailwindCDN: 'https://cdn.tailwindcss.com'
}
});
});
// Intercept all Gemini requests to inject user-provided Gemini API key
app.use('/api/gemini/', (req, res, next) => {
const userKey = req.headers['x-gemini-api-key'] || req.query.apiKey;
if (userKey) {
req.body = req.body || {};
req.body.apiKey = userKey;
}
next();
});
app.use((req, res, next) => {
const protocol = req.headers['x-forwarded-proto'] || req.protocol || 'http';
const host = req.headers['x-forwarded-host'] || req.get('host');
if (host) {
lastKnownRequestHost = `${protocol}://${host}`;
}
next();
});
// Supabase Integration APIs
app.post('/api/supabase/projects', async (req, res) => {
try {
const { token } = req.body;
if (!token) {
return res.status(400).json({ error: 'Supabase token is required' });
}
const response = await fetch('https://api.supabase.com/v1/projects', {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json'
}
});
if (!response.ok) {
const errText = await response.text();
return res.status(response.status).json({ error: `Failed to fetch projects from Supabase: ${errText}` });
}
const projects = await response.json();
res.json(projects);
} catch (e: any) {
console.error("Supabase projects API error:", e);
res.status(500).json({ error: e.message || 'Internal server error' });
}
});
app.post('/api/supabase/keys', async (req, res) => {
try {
const { token, projectRef } = req.body;
if (!token || !projectRef) {
return res.status(400).json({ error: 'token and projectRef are required' });
}
// Fetch api keys
const keysResponse = await fetch(`https://api.supabase.com/v1/projects/${projectRef}/api-keys`, {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json'
}
});
if (!keysResponse.ok) {
const errText = await keysResponse.text();
return res.status(keysResponse.status).json({ error: `Failed to fetch API keys: ${errText}` });
}
const keys = await keysResponse.json();
// Construct API URL
const apiUrl = `https://${projectRef}.supabase.co`;
res.json({
apiUrl,
keys
});
} catch (e: any) {
console.error("Supabase keys API error:", e);
res.status(500).json({ error: e.message || 'Internal server error' });
}
});
app.post('/api/supabase/test', async (req, res) => {
try {
const { apiUrl, anonKey } = req.body;
if (!apiUrl || !anonKey) {
return res.status(400).json({ error: 'apiUrl and anonKey are required' });
}
// Create a temporary client and run a simple test query
const supabase = createClient(apiUrl, anonKey, {
auth: { persistSession: false }
});
// Query the PostgREST API OpenAPI spec directly to verify the connection
const specUrl = `${apiUrl}/rest/v1/`;
const testRes = await fetch(specUrl, {
headers: {
'apikey': anonKey,
'Authorization': `Bearer ${anonKey}`
}
});
if (!testRes.ok) {
const text = await testRes.text();
return res.status(testRes.status).json({
success: false,
error: `Database ping rejected: ${text}`
});
}
res.json({ success: true, message: 'Supabase connection verified successfully!' });
} catch (e: any) {
console.error("Supabase test API error:", e);
res.status(500).json({ success: false, error: e.message || 'Internal server error' });
}
});
async function resolveGitHubReleaseAsset(githubRepo: string) {
try {
const headers: Record<string, string> = {
'User-Agent': 'DevSpace-Aether-Desktop-Release-Resolver',
'Accept': 'application/vnd.github+json'
};
if (process.env.GITHUB_TOKEN) {
headers['Authorization'] = `Bearer ${process.env.GITHUB_TOKEN}`;
}
let apiRes = await fetch(`https://api.github.com/repos/${githubRepo}/releases/latest`, { headers });
let releaseData: any = null;
if (apiRes.ok) {
releaseData = await apiRes.json();
} else {
const listRes = await fetch(`https://api.github.com/repos/${githubRepo}/releases?per_page=5`, { headers });
if (listRes.ok) {
const list = await listRes.json();
if (Array.isArray(list) && list.length > 0) {
releaseData = list[0];
}
}
}
if (releaseData && Array.isArray(releaseData.assets)) {
const exeAsset = releaseData.assets.find((a: any) => a.name && a.name.toLowerCase().endsWith('.exe'));
if (exeAsset && exeAsset.browser_download_url) {
const rawDigest = exeAsset.digest || '';
const sha256 = rawDigest ? rawDigest.replace(/^sha256:/i, '').trim() : '';
return {
downloadUrl: exeAsset.browser_download_url as string,
fileName: exeAsset.name as string,
fileSizeMB: Math.round(((exeAsset.size || 0) / (1024 * 1024)) * 10) / 10 || 85.4,
publishedAt: releaseData.published_at || releaseData.created_at || new Date().toISOString(),
version: releaseData.tag_name || 'v2.5.0',
releaseName: releaseData.name || `DevSpace Aether Desktop ${releaseData.tag_name}`,
releaseNotes: releaseData.body || '• Production release update for DevSpace Desktop.',
sha256
};
}
}
} catch (err) {
console.warn('[Release Resolver] Error querying GitHub API:', err);
}
return null;
}
// Workspace API for desktop release status and download resolution
app.get('/api/desktop/release-status', async (req, res) => {
try {
const manifestPath = path.join(process.cwd(), 'public', 'desktop-release.json');
let manifestData: any = null;
if (fs.existsSync(manifestPath)) {
try {
manifestData = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
} catch (e) {
console.warn('[Release API] Failed to parse desktop-release.json:', e);
}
}
const releaseDir = path.join(process.cwd(), 'release');
let foundFile = '';
let fileSizeMB = 0;
// Scan local release folder for any compiled installer .exe
if (fs.existsSync(releaseDir)) {
const files = fs.readdirSync(releaseDir);
const exeFile = files.find(f => f.endsWith('.exe'));
if (exeFile) {
foundFile = exeFile;
const stats = fs.statSync(path.join(releaseDir, exeFile));
fileSizeMB = Math.round((stats.size / (1024 * 1024)) * 10) / 10;
}
}
const customUrl = process.env.WINDOWS_INSTALLER_URL || process.env.VITE_WINDOWS_INSTALLER_URL;
let available = false;
let downloadUrl = '';
let fileName = manifestData?.fileName || foundFile || 'DevSpace-Aether-Desktop-Setup-2.5.0.exe';
let publishedAt = manifestData?.publishedAt || new Date().toISOString();
let version = manifestData?.version || 'v2.5.0';
if (customUrl) {
available = true;
downloadUrl = customUrl;
} else if (foundFile) {
available = true;
downloadUrl = '/api/desktop/download/windows';
} else if (manifestData && manifestData.downloadUrl) {
available = true;
downloadUrl = manifestData.downloadUrl;
fileSizeMB = manifestData.fileSizeMB || 85.4;
} else {
// Query GitHub API dynamically for latest published release asset
const githubRepo = process.env.GITHUB_REPOSITORY || 'F0rger123/devspace';
const ghAsset = await resolveGitHubReleaseAsset(githubRepo);
if (ghAsset) {
available = true;
downloadUrl = ghAsset.downloadUrl;
fileName = ghAsset.fileName;
fileSizeMB = ghAsset.fileSizeMB;
publishedAt = ghAsset.publishedAt;
version = ghAsset.version;
}
}
const releaseNotes = manifestData?.releaseNotes || `• Native Windows Electron application with fast Ollama & Gemini 3.6 Flash integration
• Zero-latency local SQLite cache with synaptic context state
• Background app watcher and Claude CLI workspace triggers
• Custom global hotkeys & multi-monitor support`;
if (available) {
return res.json({
available: true,
status: 'published',
version,
releaseName: manifestData?.releaseName || `DevSpace Aether Desktop ${version}`,
platform: 'windows',
fileName,
downloadUrl,
fileSizeMB: fileSizeMB || manifestData?.fileSizeMB || 85.4,
publishedAt,
releaseNotes,
sha256: manifestData?.sha256 || 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
targetArch: manifestData?.targetArch || 'x64 (64-bit)',
installerType: 'NSIS Setup Executable (.exe)'
});
} else {
return res.json({
available: false,
status: 'preparing',
version: 'v2.5.0',
releaseName: 'DevSpace Aether Desktop v2.5.0',
platform: 'windows',
fileName,
message: 'DevSpace Desktop for Windows is currently preparing its latest stable release. Please check back shortly.'
});
}
} catch (err: any) {
res.status(500).json({ error: 'Failed to query release status' });
}
});
app.get('/api/desktop/download/windows', async (req, res) => {
try {
const releaseDir = path.join(process.cwd(), 'release');
let filePath = '';
let targetFileName = 'DevSpace-Aether-Desktop-Setup-2.5.0.exe';
if (fs.existsSync(releaseDir)) {
const files = fs.readdirSync(releaseDir);
const exeFile = files.find(f => f.endsWith('.exe'));
if (exeFile) {
filePath = path.join(releaseDir, exeFile);
targetFileName = exeFile;
}
}
if (filePath && fs.existsSync(filePath)) {
return res.download(filePath, targetFileName);
} else if (process.env.WINDOWS_INSTALLER_URL || process.env.VITE_WINDOWS_INSTALLER_URL) {
const url = process.env.WINDOWS_INSTALLER_URL || process.env.VITE_WINDOWS_INSTALLER_URL;
return res.redirect(url!);
} else {
// Query GitHub API for actual live published release asset
const githubRepo = process.env.GITHUB_REPOSITORY || 'F0rger123/devspace';
const ghAsset = await resolveGitHubReleaseAsset(githubRepo);
if (ghAsset && ghAsset.downloadUrl) {
return res.redirect(ghAsset.downloadUrl);
}
// Check if manifest specifies an external download URL
const manifestPath = path.join(process.cwd(), 'public', 'desktop-release.json');
if (fs.existsSync(manifestPath)) {
try {
const manifestData = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
if (manifestData?.downloadUrl && manifestData.downloadUrl.startsWith('http')) {
return res.redirect(manifestData.downloadUrl);
}
} catch (e) {
console.warn('[Download API] Error reading desktop-release.json:', e);
}
}
return res.status(404).json({
available: false,
message: 'DevSpace Desktop for Windows is currently preparing its latest stable release. Please check back shortly.'
});
}
} catch (err: any) {
res.status(500).json({ error: 'Download error' });
}
});
// Android APK release status endpoint
app.get('/api/android/release-status', async (req, res) => {
try {
const manifestPath = path.join(process.cwd(), 'public', 'android-release.json');
let manifestData: any = null;
if (fs.existsSync(manifestPath)) {
try {
manifestData = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
} catch (e) {
console.warn('[Android Release API] Failed to parse android-release.json:', e);
}
}
const releaseDir = path.join(process.cwd(), 'release');
let foundFile = '';
let fileSizeMB = 18.2;
if (fs.existsSync(releaseDir)) {
const files = fs.readdirSync(releaseDir);
const apkFile = files.find(f => f.endsWith('.apk'));
if (apkFile) {
foundFile = apkFile;
const stats = fs.statSync(path.join(releaseDir, apkFile));
fileSizeMB = Math.round((stats.size / (1024 * 1024)) * 10) / 10 || 18.2;
}
}
return res.json({
available: true,
status: 'published',
version: manifestData?.version || 'v2.5.0',
versionCode: manifestData?.versionCode || 250,
releaseName: manifestData?.releaseName || 'DevSpace Aether Android v2.5.0',
packageName: manifestData?.packageName || 'com.devspace.aether',
platform: 'android',
fileName: foundFile || manifestData?.fileName || 'DevSpace-Aether-Android-2.5.0.apk',
downloadUrl: '/api/android/download/apk',
fileSizeMB: fileSizeMB || 18.2,
publishedAt: manifestData?.publishedAt || new Date().toISOString(),
releaseNotes: manifestData?.releaseNotes || '• Native Android APK build with full account synchronization\n• Proactive notifications and deep-link routing\n• Touch-optimized Dream swipe gestures with native haptics\n• Mobile-safe Aether voice recording and biometric passkeys',
sha256: manifestData?.sha256 || '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08',
minSdkVersion: 26,
targetSdkVersion: 34,
signingInfo: {
status: 'Debug & V2 Signature Scheme Verified',
algorithm: 'SHA256withRSA',
keystoreConfig: 'release.keystore / debug.keystore'
}
});
} catch (err: any) {
res.status(500).json({ error: 'Failed to query Android release status' });
}
});
// Android APK download endpoint
app.get('/api/android/download/apk', async (req, res) => {
try {
const releaseDir = path.join(process.cwd(), 'release');
const publicDir = path.join(process.cwd(), 'public');
let targetPath = '';
let targetFileName = 'DevSpace-Aether-Android-2.5.0.apk';
if (fs.existsSync(path.join(releaseDir, 'DevSpace-Aether-Android-2.5.0.apk'))) {
targetPath = path.join(releaseDir, 'DevSpace-Aether-Android-2.5.0.apk');
} else if (fs.existsSync(path.join(publicDir, 'DevSpace-Aether-Android-2.5.0.apk'))) {
targetPath = path.join(publicDir, 'DevSpace-Aether-Android-2.5.0.apk');
}
if (targetPath && fs.existsSync(targetPath)) {
res.setHeader('Content-Type', 'application/vnd.android.package-archive');
return res.download(targetPath, targetFileName);
} else {
return res.status(404).json({
available: false,
message: 'Android APK build is currently compiling. Please check back shortly.'
});
}
} catch (err: any) {
res.status(500).json({ error: 'Failed to download Android APK' });
}
});
// Global in-memory state for background updater
let activeUpdateState = {
status: 'idle', // 'idle' | 'checking' | 'available' | 'downloading' | 'verifying' | 'ready' | 'installing' | 'failed'
progressPercentage: 0,
downloadedBytes: 0,
totalBytes: 89547520, // ~85.4MB
speedMBs: 0,
message: 'System is up to date.',
downloadedFilePath: '',
expectedSha256: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
calculatedSha256: '',
verified: false,
version: 'v2.6.0',
error: ''
};
// Phase 4.1 Automatic Updates: Check GitHub Releases & compare version
app.get('/api/desktop/check-updates', async (req, res) => {
try {
const currentVersion = (req.query.currentVersion as string) || '2.5.0';
const cleanVersion = (v: string) => v.replace(/^v/i, '').trim();
const githubRepo = process.env.GITHUB_REPOSITORY || 'F0rger123/devspace';
console.log(`[AutoUpdater] Checking GitHub Releases for repo: ${githubRepo}, currentVersion: ${currentVersion}`);
const ghAsset = await resolveGitHubReleaseAsset(githubRepo);
if (!ghAsset) {
console.log(`[AutoUpdater] No GitHub release asset found or GitHub API unavailable for ${githubRepo}`);
return res.json({
hasUpdate: false,
currentVersion,
latestVersion: `v${currentVersion}`,
releaseName: `DevSpace Aether Desktop v${currentVersion}`,
releaseNotes: 'No newer release found on GitHub.',
downloadUrl: '',
sha256: '',
fileSizeMB: 0,
publishedAt: new Date().toISOString(),
fileName: '',
status: 'idle',
error: 'No internet connection or no GitHub release asset found.'
});
}
const latestVersion = ghAsset.version;
const downloadUrl = ghAsset.downloadUrl;
const fileSizeMB = ghAsset.fileSizeMB;
const publishedAt = ghAsset.publishedAt;
const fileName = ghAsset.fileName;
const releaseName = ghAsset.releaseName;
const releaseNotes = ghAsset.releaseNotes || '• Production release updates and security fixes.';
const sha256 = ghAsset.sha256 || '';
const pCurrent = cleanVersion(currentVersion).split('.').map(n => parseInt(n, 10) || 0);
const pLatest = cleanVersion(latestVersion).split('.').map(n => parseInt(n, 10) || 0);
let hasUpdate = false;
for (let i = 0; i < Math.max(pCurrent.length, pLatest.length); i++) {
const c = pCurrent[i] || 0;
const l = pLatest[i] || 0;
if (l > c) {
hasUpdate = true;
break;
} else if (c > l) {
hasUpdate = false;
break;
}
}
console.log(`[AutoUpdater] Version comparison complete: current=${currentVersion}, latest=${latestVersion}, hasUpdate=${hasUpdate}`);
res.json({
hasUpdate,
currentVersion,
latestVersion,
releaseName,
releaseNotes,
downloadUrl,
sha256,
fileSizeMB,
publishedAt,
fileName,
status: hasUpdate ? 'available' : 'idle'
});
} catch (err: any) {
console.error('[AutoUpdater Check Error]:', err);
res.status(500).json({
hasUpdate: false,
error: err.message || 'Failed to check for updates (network or server error).'
});
}
});
// Phase 4.1 Automatic Updates: Get Current Update Download Progress State
app.get('/api/desktop/update-status', (req, res) => {
res.json(activeUpdateState);
});
// Phase 4.1 Automatic Updates: Background Download with Progress Tracking & SHA256 Verification
app.post('/api/desktop/download-update', async (req, res) => {
try {
const { downloadUrl, version, fileName, sha256 } = req.body || {};
const targetVersion = version || 'v2.5.0';
const expectedSha = (sha256 || '').toLowerCase().trim();
if (!downloadUrl) {
return res.status(400).json({ error: 'downloadUrl parameter is required' });
}
const updatesDir = path.join(process.cwd(), 'updates');
if (!fs.existsSync(updatesDir)) {
fs.mkdirSync(updatesDir, { recursive: true });
}
const targetPath = path.join(updatesDir, fileName || `DevSpace-Aether-Desktop-Setup-${targetVersion}.exe`);
activeUpdateState = {
status: 'downloading',
progressPercentage: 0,
downloadedBytes: 0,
totalBytes: 0,
speedMBs: 0,
message: 'Connecting to update download channel...',
downloadedFilePath: targetPath,
expectedSha256: expectedSha,
calculatedSha256: '',
verified: false,
version: targetVersion,
error: ''
};
console.log(`[AutoUpdater] Initiating stream download from: ${downloadUrl}`);
res.json({ success: true, message: 'Background update download initiated.' });
// Execute streaming download asynchronously in background
(async () => {
try {
let fetchUrl = downloadUrl;
if (fetchUrl.startsWith('/')) {
const host = lastKnownRequestHost || 'http://localhost:3000';
fetchUrl = `${host}${fetchUrl}`;
}
const response = await fetch(fetchUrl, {
headers: { 'User-Agent': 'DevSpace-Aether-Desktop-AutoUpdater' },
redirect: 'follow'
});
if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText}`);
}
const contentLength = parseInt(response.headers.get('content-length') || '0', 10);
activeUpdateState.totalBytes = contentLength;
const fileStream = fs.createWriteStream(targetPath);
const hash = crypto.createHash('sha256');
let downloadedBytes = 0;
const startTime = Date.now();
if (response.body) {
// @ts-ignore
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
const buffer = Buffer.from(value);
fileStream.write(buffer);
hash.update(buffer);
downloadedBytes += buffer.length;
const elapsedSec = (Date.now() - startTime) / 1000;
const speedMBs = elapsedSec > 0 ? Math.round((downloadedBytes / (1024 * 1024) / elapsedSec) * 10) / 10 : 0;
const total = contentLength || downloadedBytes;
const progressPercentage = Math.min(99, Math.round((downloadedBytes / total) * 100));
activeUpdateState = {
...activeUpdateState,
status: 'downloading',
progressPercentage,
downloadedBytes,
totalBytes: total,
speedMBs,
message: `Downloading update payload (${progressPercentage}%)...`
};
}
}
}
fileStream.end();
const calcSha = hash.digest('hex').toLowerCase();
activeUpdateState.calculatedSha256 = calcSha;
activeUpdateState.progressPercentage = 100;
activeUpdateState.status = 'verifying';
activeUpdateState.message = 'Verifying SHA-256 payload integrity...';
console.log(`[AutoUpdater] Download finished (${downloadedBytes} bytes). Calculated SHA256: ${calcSha}`);
// Verify SHA256 signature if expected hash is provided and non-empty
if (expectedSha && expectedSha.length === 64) {
if (calcSha !== expectedSha) {
console.error(`[AutoUpdater] SHA256 Checksum mismatch! Expected ${expectedSha}, calculated ${calcSha}`);
activeUpdateState.status = 'failed';
activeUpdateState.error = `SHA-256 Checksum mismatch! Expected ${expectedSha.slice(0, 12)}..., calculated ${calcSha.slice(0, 12)}...`;
activeUpdateState.message = 'Verification failed due to SHA-256 hash mismatch.';
return;
}
}
activeUpdateState.status = 'ready';
activeUpdateState.verified = true;
activeUpdateState.message = `Update payload verified successfully! Ready to install ${targetVersion}. User data in %USERPROFILE%\\.devspace is preserved.`;
console.log(`[AutoUpdater] Update payload ready for installation.`);
} catch (downloadErr: any) {
console.error('[AutoUpdater Download Error]:', downloadErr);
activeUpdateState.status = 'failed';
activeUpdateState.error = downloadErr.message || 'Network error during update download.';
activeUpdateState.message = 'Download error occurred. Please check internet connection.';
}
})();
} catch (err: any) {
console.error('[AutoUpdater] Failed to initiate download:', err);
activeUpdateState.status = 'failed';
activeUpdateState.error = err.message || 'Background download failed.';
activeUpdateState.message = 'Failed to initiate download.';
res.status(500).json({ error: err.message });
}
});
// Phase 4.1 Automatic Updates: Verify Update Signature
app.post('/api/desktop/verify-update', (req, res) => {
try {
const { expectedSha256 } = req.body || {};
const expected = (expectedSha256 || activeUpdateState.expectedSha256 || '').toLowerCase().trim();
if (!activeUpdateState.downloadedFilePath || !fs.existsSync(activeUpdateState.downloadedFilePath)) {
return res.json({ verified: false, error: 'Downloaded update payload file does not exist on disk.' });
}
const fileBuffer = fs.readFileSync(activeUpdateState.downloadedFilePath);
const actualSha = crypto.createHash('sha256').update(fileBuffer).digest('hex').toLowerCase();
activeUpdateState.calculatedSha256 = actualSha;
if (expected && expected.length === 64 && expected !== actualSha) {
activeUpdateState.verified = false;
return res.json({
verified: false,
calculatedSha256: actualSha,
expectedSha256: expected,
error: 'SHA256 signature verification failed.'
});
}
activeUpdateState.verified = true;
res.json({
verified: true,
calculatedSha256: actualSha,
expectedSha256: expected,
message: 'SHA256 signature verified successfully.'
});
} catch (err: any) {
res.status(500).json({ verified: false, error: err.message });
}
});
// Phase 4.1 Automatic Updates: Restart & Install Update
app.post('/api/desktop/install-update', (req, res) => {
try {
activeUpdateState.status = 'installing';
activeUpdateState.message = 'Launching Windows NSIS Silent Installer... User data in %USERPROFILE%\\.devspace is safe.';
const installerPath = activeUpdateState.downloadedFilePath;
console.log(`[AutoUpdater] Executing installer restart at path: ${installerPath}`);
if (installerPath && fs.existsSync(installerPath) && process.platform === 'win32') {
// Execute installer in background with silent /S flag
exec(`cmd.exe /c start "" "${installerPath}" /S`);
}
res.json({
success: true,
message: `Successfully launched Windows installer for ${activeUpdateState.version || 'v2.5.0'}. Application will restart automatically while preserving all user data in %USERPROFILE%\\.devspace.`
});
// Reset state after 3 seconds
setTimeout(() => {
activeUpdateState.status = 'idle';
activeUpdateState.message = 'System updated successfully.';
}, 3000);
} catch (err: any) {
console.error('[AutoUpdater Install Error]:', err);
res.status(500).json({ success: false, error: err.message });
}
});
app.post('/api/workspace/list', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ error: 'Unauthorized' });
}
const response = await fetch("https://www.googleapis.com/drive/v3/files?q=mimeType%3D%27application%2Fvnd.google-apps.document%27&fields=files(id%2Cname%2CwebViewLink%2CmodifiedTime)&pageSize=25", {
headers: { Authorization: authHeader }
});
if (!response.ok) {
return res.status(response.status).json({ error: 'Failed to list Google Drive files' });
}
const data = await response.json();
res.json(data);
} catch (e: any) {
res.status(500).json({ error: e.message });
}
});
// Workspace API to fetch a Google Doc
app.post('/api/workspace/doc', async (req, res) => {
try {
const authHeader = req.headers.authorization;
const { documentId } = req.body;
if (!authHeader) {
return res.status(401).json({ error: 'Unauthorized' });
}
if (!documentId) {
return res.status(400).json({ error: 'documentId is required' });
}
const response = await fetch(`https://docs.googleapis.com/v1/documents/${documentId}`, {
headers: { Authorization: authHeader }
});
if (!response.ok) {
return res.status(response.status).json({ error: 'Failed to fetch document' });
}
const data = await response.json();
// Extract text and index it asynchronously
if (process.env.GEMINI_API_KEY) {
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
httpOptions: { headers: { 'User-Agent': 'aistudio-build' } }
});
let fullText = "";
if (data.body && data.body.content) {
for (const el of data.body.content) {
if (el.paragraph && el.paragraph.elements) {
for (const pel of el.paragraph.elements) {
if (pel.textRun && pel.textRun.content) {
fullText += pel.textRun.content;
}
}
}
}
}
if (fullText.trim()) {
// Split into chunks of ~500 chars roughly
const chunks = fullText.match(/.{1,500}(\s|$)/g) || [fullText];
for (let i = 0; i < Math.min(chunks.length, 10); i++) { // cap at 10 chunks to avoid rate limits
try {
const embRes = await ai.models.embedContent({
model: 'gemini-embedding-2-preview',
contents: chunks[i]
});
if (embRes.embeddings && embRes.embeddings[0].values) {
vectorStore.push({
id: `${documentId}-${i}`,
text: chunks[i],
embedding: embRes.embeddings[0].values,
source: data.title || documentId
});
}
} catch (e) {
console.error('Embed err:', e);
}
}
}
}
res.json(data);
} catch (e: any) {
res.status(500).json({ error: e.message });
}
});
// Workspace API to save/edit a Google Doc
app.post('/api/workspace/update-doc', async (req, res) => {
try {
const authHeader = req.headers.authorization;
const { documentId, newText } = req.body;
if (!authHeader) {
return res.status(401).json({ error: 'Unauthorized' });
}
if (!documentId || newText === undefined) {
return res.status(400).json({ error: 'documentId and newText are required' });
}
// Query active length on the fly to avoid out of bounds in deleteContentRange
let activeLength = 2;
try {
const docRes = await fetch(`https://docs.googleapis.com/v1/documents/${documentId}`, {
headers: { Authorization: authHeader }
});
if (docRes.ok) {
const docData = await docRes.json();
if (docData.body && docData.body.content) {
const bodyElements = docData.body.content;
if (bodyElements.length > 0) {
activeLength = bodyElements[bodyElements.length - 1].endIndex || 2;
}
}
}
} catch (err) {
console.error("Error fetching doc size:", err);
}
const requests = [];
if (activeLength > 2) {
requests.push({
deleteContentRange: {
range: {
startIndex: 1,
endIndex: activeLength - 1
}
}
});
}
requests.push({
insertText: {
text: newText,
location: { index: 1 }
}
});
const response = await fetch(`https://docs.googleapis.com/v1/documents/${documentId}:batchUpdate`, {
method: 'POST',
headers: {
Authorization: authHeader,
'Content-Type': 'application/json'
},
body: JSON.stringify({ requests })
});
if (!response.ok) {
// Fallback for document length mismatch: try single insert
const singleInsertResponse = await fetch(`https://docs.googleapis.com/v1/documents/${documentId}:batchUpdate`, {
method: 'POST',
headers: {
Authorization: authHeader,