-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3085 lines (2893 loc) · 131 KB
/
Copy pathserver.js
File metadata and controls
3085 lines (2893 loc) · 131 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
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const path = require('path');
const crypto = require('crypto');
const bcrypt = require('bcryptjs');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const { getConfig, reloadConfig, updateConfig, saveConfig, replaceConfig } = require('./lib/config.js');
const { ollamaChatStream, ollamaChatWithTools, listModels, getModelContextWindow } = require('./lib/ollama.js');
const { authMiddleware, authenticate, listUsers, createUser, updateUser, deleteUser, requireAdmin } = require('./lib/auth.js');
const { runCode } = require('./lib/runCode.js');
const { readFile, writeFile, listFiles } = require('./lib/selfUpdate.js');
const skillsLib = require('./lib/skills.js');
const personalityLib = require('./lib/personality.js');
const heartbeatLib = require('./lib/heartbeat.js');
const searxngLib = require('./lib/searxng.js');
const fetchUrlLib = require('./lib/fetchUrl.js');
const structuredMemory = require('./lib/structuredMemory.js');
const chatStore = require('./lib/chatStore.js');
const channelLinks = require('./lib/channelLinks.js');
const emailLib = require('./lib/email.js');
const logger = require('./lib/logger.js');
const systemPrompt = require('./lib/systemPrompt.js');
const chatRunner = require('./lib/chatRunner.js');
const { executeSchedulerTool, getSchedulerToolDefinitions } = require('./lib/toolHandlers.js');
const agentLoopTools = require('./lib/agentLoopTools.js');
const chatHistorySearch = require('./lib/chatHistorySearch.js');
const pipelineRunner = require('./lib/pipelineRunner.js');
const pipelineObservability = require('./lib/pipelineObservability.js');
const projectStore = require('./lib/projectStore.js');
const projectImport = require('./lib/projectImport.js');
const ragLib = require('./lib/rag.js');
const agentStore = require('./lib/agentStore.js');
const agentRunner = require('./lib/agentRunner.js');
const myDataFs = require('./lib/myDataFs.js');
const { buildMessagesWithAttachments } = require('./lib/chatAttachments.js');
const hiveStore = require('./lib/hiveMind/store.js');
const commandCenter = require('./lib/commandCenter/coordinator.js');
const missionReporter = require('./lib/commandCenter/missionReporter.js');
const commandCenterAdmin = require('./lib/commandCenter/adminControls.js');
const app = express();
const PUBLIC = path.join(__dirname, 'public');
const SERVER_INSTANCE_ID = crypto.randomUUID();
// ---------------------------------------------------------------------------
// Security headers (helmet)
// Configure CSP to allow the CDN libraries the frontend actually uses
// ---------------------------------------------------------------------------
app.use(helmet({
// Disable HSTS — this is a local HTTP server, not a public HTTPS site.
// HSTS would cause browsers to remember to use HTTPS and break the connection.
strictTransportSecurity: false,
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "https://cdn.jsdelivr.net"],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://cdn.jsdelivr.net"],
fontSrc: ["'self'", "https://fonts.googleapis.com", "https://fonts.gstatic.com"],
connectSrc: ["'self'"],
imgSrc: ["'self'", "data:"],
frameSrc: ["'self'"],
objectSrc: ["'none'"],
// Disable upgrade-insecure-requests — it tells browsers to force HTTPS,
// which breaks a local HTTP-only server.
upgradeInsecureRequests: null
}
}
}));
// ---------------------------------------------------------------------------
// Rate limiters
// ---------------------------------------------------------------------------
const chatLimiter = rateLimit({
windowMs: 60 * 1000,
max: 60,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests — slow down.' }
});
const runLimiter = rateLimit({
windowMs: 60 * 1000,
max: 20,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests — slow down.' }
});
// ---------------------------------------------------------------------------
// Body parsing (large limit for project import: PDFs/images sent as base64)
// ---------------------------------------------------------------------------
const JSON_LIMIT = '50mb';
app.use(bodyParser.json({ limit: JSON_LIMIT }));
app.use(bodyParser.urlencoded({ extended: true, limit: JSON_LIMIT }));
// ---------------------------------------------------------------------------
// Session — secret generated once and persisted in config
// ---------------------------------------------------------------------------
let sessionSecret = getConfig().sessionSecret;
if (!sessionSecret) {
sessionSecret = crypto.randomBytes(32).toString('hex');
updateConfig({ sessionSecret });
logger.info('Generated and saved new session secret');
}
app.use(session({
secret: sessionSecret,
resave: false,
saveUninitialized: false,
cookie: { secure: false, sameSite: 'strict', maxAge: 7 * 24 * 60 * 60 * 1000 }
}));
app.use(authMiddleware);
app.use('/static', express.static(PUBLIC));
// ---------------------------------------------------------------------------
// System prompt builder (delegates to lib)
// ---------------------------------------------------------------------------
function buildSystemPrompt(customInstructions = '', userContext = '') {
return systemPrompt.buildSystemPrompt(customInstructions, userContext);
}
// ---------------------------------------------------------------------------
// Routes — public
// ---------------------------------------------------------------------------
app.get('/', (req, res) => {
if (req.session && req.session.user) return res.redirect('/dashboard');
res.redirect('/login');
});
app.get('/login', (req, res) => {
if (req.session && req.session.user) return res.redirect('/app');
res.sendFile(path.join(PUBLIC, 'login.html'));
});
app.post('/api/login', async (req, res) => {
const { username, password } = req.body || {};
if (!username || !password) {
return res.status(400).json({ error: 'Username and password required' });
}
try {
const user = await authenticate(username, password);
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
req.session.user = { username: user.username, role: user.role };
return res.json({ ok: true, user });
} catch (e) {
logger.error('POST /api/login:', e.message);
res.status(500).json({ error: 'Authentication failed' });
}
});
app.post('/api/logout', (req, res) => {
req.session.destroy((e) => {
if (e) logger.warn('Session destroy error:', e.message);
});
res.json({ ok: true });
});
app.get('/api/me', (req, res) => {
const u = req.currentUser;
if (!u) return res.status(401).json({ error: 'Not authenticated' });
res.json({ username: u.username, role: u.role });
});
app.post('/api/users/me/password', async (req, res) => {
const u = req.currentUser;
if (!u) return res.status(401).json({ error: 'Not authenticated' });
const { currentPassword, newPassword } = req.body || {};
if (!currentPassword || !newPassword) {
return res.status(400).json({ error: 'currentPassword and newPassword are required' });
}
if (typeof newPassword !== 'string' || newPassword.length < 8) {
return res.status(400).json({ error: 'New password must be at least 8 characters' });
}
try {
const verified = await authenticate(u.username, currentPassword);
if (!verified) return res.status(403).json({ error: 'Current password is incorrect' });
await updateUser(u.username, { password: newPassword });
logger.info(`Password changed for user: ${u.username}`);
res.json({ ok: true });
} catch (e) {
logger.error('POST /api/users/me/password:', e.message);
res.status(500).json({ error: 'Failed to update password' });
}
});
// Serve AI avatar image (if uploaded). This is a simple file under data/.
app.get('/static/ai-avatar', (req, res) => {
try {
const fs = require('fs');
const DATA_DIR = path.join(__dirname, 'data');
const candidates = ['ai-avatar.png', 'ai-avatar.jpg', 'ai-avatar.jpeg', 'ai-avatar.webp'];
for (const name of candidates) {
const filePath = path.join(DATA_DIR, name);
if (fs.existsSync(filePath)) {
return res.sendFile(filePath);
}
}
res.status(404).end();
} catch (e) {
logger.warn('GET /static/ai-avatar error:', e.message);
res.status(500).end();
}
});
// ---------------------------------------------------------------------------
// Routes — protected pages
// ---------------------------------------------------------------------------
// Redirect non-admins away from admin-only pages
function adminPageGuard(req, res, next) {
if (!req.currentUser || req.currentUser.role !== 'admin') return res.redirect('/dashboard');
next();
}
app.get('/profile', (req, res) => res.sendFile(path.join(PUBLIC, 'profile.html')));
app.get('/dashboard', (req, res) => res.sendFile(path.join(PUBLIC, 'dashboard.html')));
app.get('/app', (req, res) => res.sendFile(path.join(PUBLIC, 'app.html')));
app.get('/skills', (req, res) => res.sendFile(path.join(PUBLIC, 'skills.html')));
app.get('/rag', (req, res) => res.sendFile(path.join(PUBLIC, 'rag.html')));
app.get('/projects', (req, res) => res.sendFile(path.join(PUBLIC, 'projects.html')));
app.get('/project', (req, res) => res.sendFile(path.join(PUBLIC, 'project.html')));
app.get('/command-center', (req, res) => res.sendFile(path.join(PUBLIC, 'command-center.html')));
app.get('/my-data', (req, res) => res.sendFile(path.join(PUBLIC, 'my-data.html')));
// Admin-only pages
app.get('/config', adminPageGuard, (req, res) => res.sendFile(path.join(PUBLIC, 'config.html')));
app.get('/personality', adminPageGuard, (req, res) => res.sendFile(path.join(PUBLIC, 'personality.html')));
app.get('/heartbeat', adminPageGuard, (req, res) => res.sendFile(path.join(PUBLIC, 'heartbeat.html')));
app.get('/agents', adminPageGuard, (req, res) => res.sendFile(path.join(PUBLIC, 'agents.html')));
app.get('/pipelines', adminPageGuard, (req, res) => res.sendFile(path.join(PUBLIC, 'pipelines.html')));
app.get('/editor', adminPageGuard, (req, res) => res.sendFile(path.join(PUBLIC, 'editor.html')));
app.get('/users', adminPageGuard, (req, res) => res.sendFile(path.join(PUBLIC, 'users.html')));
app.get('/debug', adminPageGuard, (req, res) => res.sendFile(path.join(PUBLIC, 'debug.html')));
app.get('/autoagent', adminPageGuard, (req, res) => res.sendFile(path.join(PUBLIC, 'autoagent.html')));
// ---------------------------------------------------------------------------
// Personality & memory
// ---------------------------------------------------------------------------
app.get('/api/personality', (req, res) => {
try {
const scopeUser = (req.currentUser && req.currentUser.username) || (req.session && req.session.user) || '';
res.json({ content: personalityLib.readPersonality(scopeUser) });
} catch (e) {
logger.error('GET /api/personality:', e.message);
res.status(500).json({ error: e.message });
}
});
app.put('/api/personality', (req, res) => {
try {
const scopeUser = (req.currentUser && req.currentUser.username) || (req.session && req.session.user) || '';
personalityLib.writePersonality(req.body?.content ?? '', scopeUser);
res.json({ ok: true });
} catch (e) {
logger.error('PUT /api/personality:', e.message);
res.status(500).json({ error: e.message });
}
});
app.get('/api/memory', (req, res) => {
try {
const scopeUser = (req.currentUser && req.currentUser.username) || (req.session && req.session.user) || '';
res.json({ content: personalityLib.readMemory(scopeUser) });
} catch (e) {
logger.error('GET /api/memory:', e.message);
res.status(500).json({ error: e.message });
}
});
app.put('/api/memory', (req, res) => {
try {
const scopeUser = (req.currentUser && req.currentUser.username) || (req.session && req.session.user) || '';
personalityLib.writeMemory(req.body?.content ?? '', scopeUser);
res.json({ ok: true });
} catch (e) {
logger.error('PUT /api/memory:', e.message);
res.status(500).json({ error: e.message });
}
});
app.post('/api/memory/append', (req, res) => {
try {
const text = req.body?.text ?? '';
if (!text.trim()) return res.status(400).json({ error: 'text required' });
const scopeUser = (req.currentUser && req.currentUser.username) || (req.session && req.session.user) || '';
personalityLib.appendMemory(text, scopeUser);
res.json({ ok: true });
} catch (e) {
logger.error('POST /api/memory/append:', e.message);
res.status(500).json({ error: e.message });
}
});
app.get('/api/behavior', (req, res) => {
try {
const scopeUser = (req.currentUser && req.currentUser.username) || (req.session && req.session.user) || '';
res.json({ content: personalityLib.readBehavior(scopeUser) });
} catch (e) {
logger.error('GET /api/behavior:', e.message);
res.status(500).json({ error: e.message });
}
});
app.put('/api/behavior', (req, res) => {
try {
const scopeUser = (req.currentUser && req.currentUser.username) || (req.session && req.session.user) || '';
personalityLib.writeBehavior(req.body?.content ?? '', scopeUser);
res.json({ ok: true });
} catch (e) {
logger.error('PUT /api/behavior:', e.message);
res.status(500).json({ error: e.message });
}
});
// ---------------------------------------------------------------------------
// Projects (isolated project-specific chats and memory)
// ---------------------------------------------------------------------------
app.get('/api/projects', (req, res) => {
try {
const all = projectStore.listProjects();
const user = req.currentUser;
if (!user || user.role === 'admin') {
return res.json(all);
}
const visible = all.filter((p) => {
if (p.owner && p.owner === user.username) return true;
if (Array.isArray(p.shares)) {
return p.shares.some((s) => s.username === user.username);
}
return false;
});
res.json(visible);
} catch (e) {
logger.error('GET /api/projects:', e.message);
res.status(500).json({ error: e.message });
}
});
// Project reports (multiple: each has name, schedule, toEmail, projectIds, reportPrompt, createdBy)
app.get('/api/projects/reports', (req, res) => {
try {
const projectReport = require('./lib/projectReport.js');
let reports = projectReport.getReports();
// Non-admins only see their own reports
if (!req.currentUser || req.currentUser.role !== 'admin') {
const me = req.currentUser ? req.currentUser.username : '';
reports = reports.filter((r) => r.createdBy === me);
}
res.json(reports);
} catch (e) {
logger.error('GET /api/projects/reports:', e.message);
res.status(500).json({ error: e.message });
}
});
app.post('/api/projects/reports', (req, res) => {
try {
const projectReport = require('./lib/projectReport.js');
const body = req.body || {};
const reports = projectReport.getReports();
const newReport = projectReport.normalizeReport({
id: projectReport.newReportId(),
name: body.name,
enabled: body.enabled,
schedule: body.schedule,
toEmail: body.toEmail,
projectIds: Array.isArray(body.projectIds) ? body.projectIds : [],
reportPrompt: body.reportPrompt,
createdBy: req.currentUser ? req.currentUser.username : ''
});
reports.push(newReport);
projectReport.persistReports(reports);
res.status(201).json(newReport);
} catch (e) {
logger.error('POST /api/projects/reports:', e.message);
res.status(500).json({ error: e.message });
}
});
app.get('/api/projects/reports/:reportId', (req, res) => {
try {
const projectReport = require('./lib/projectReport.js');
const report = projectReport.getReports().find((r) => r.id === req.params.reportId);
if (!report) return res.status(404).json({ error: 'Report not found' });
const isAdmin = req.currentUser && req.currentUser.role === 'admin';
if (!isAdmin && report.createdBy !== (req.currentUser ? req.currentUser.username : '')) {
return res.status(403).json({ error: 'Access denied' });
}
res.json(report);
} catch (e) {
logger.error('GET /api/projects/reports/:reportId:', e.message);
res.status(500).json({ error: e.message });
}
});
app.put('/api/projects/reports/:reportId', (req, res) => {
try {
const projectReport = require('./lib/projectReport.js');
const body = req.body || {};
const reports = projectReport.getReports();
const idx = reports.findIndex((r) => r.id === req.params.reportId);
if (idx === -1) return res.status(404).json({ error: 'Report not found' });
const isAdmin = req.currentUser && req.currentUser.role === 'admin';
if (!isAdmin && reports[idx].createdBy !== (req.currentUser ? req.currentUser.username : '')) {
return res.status(403).json({ error: 'Access denied' });
}
const updated = projectReport.normalizeReport({ ...reports[idx], ...body, id: reports[idx].id });
// Only admins may reassign createdBy
if (!isAdmin) updated.createdBy = reports[idx].createdBy;
reports[idx] = updated;
projectReport.persistReports(reports);
res.json(updated);
} catch (e) {
logger.error('PUT /api/projects/reports/:reportId:', e.message);
res.status(500).json({ error: e.message });
}
});
app.delete('/api/projects/reports/:reportId', (req, res) => {
try {
const projectReport = require('./lib/projectReport.js');
const all = projectReport.getReports();
const report = all.find((r) => r.id === req.params.reportId);
if (!report) return res.status(404).json({ error: 'Report not found' });
const isAdmin = req.currentUser && req.currentUser.role === 'admin';
if (!isAdmin && report.createdBy !== (req.currentUser ? req.currentUser.username : '')) {
return res.status(403).json({ error: 'Access denied' });
}
projectReport.persistReports(all.filter((r) => r.id !== req.params.reportId));
res.json({ ok: true });
} catch (e) {
logger.error('DELETE /api/projects/reports/:reportId:', e.message);
res.status(500).json({ error: e.message });
}
});
app.post('/api/projects/reports/:reportId/send', (req, res) => {
const reportId = req.params.reportId;
try {
const projectReport = require('./lib/projectReport.js');
const reports = projectReport.getReports();
const report = reports.find((r) => r.id === reportId);
if (!report) {
return res.status(404).json({ ok: false, error: 'Report not found.', code: 'REPORT_NOT_FOUND' });
}
const isAdmin = req.currentUser && req.currentUser.role === 'admin';
if (!isAdmin && report.createdBy !== (req.currentUser ? req.currentUser.username : '')) {
return res.status(403).json({ ok: false, error: 'Access denied.', code: 'ACCESS_DENIED' });
}
if (!report.toEmail || !String(report.toEmail).trim()) {
return res.status(400).json({ ok: false, error: 'Report has no email address.', code: 'REPORT_NO_EMAIL' });
}
if (!Array.isArray(report.projectIds) || report.projectIds.length === 0) {
return res.status(400).json({ ok: false, error: 'Report has no projects selected.', code: 'REPORT_NO_PROJECTS' });
}
const config = getConfig();
const emailCfg = config.email || {};
if (!emailCfg.host || !emailCfg.enabled || !emailCfg.from) {
return res.status(400).json({ ok: false, error: 'Email not configured or disabled in Config.', code: 'EMAIL_NOT_CONFIGURED' });
}
// Run send in background so the request doesn't time out during report generation
projectReport.sendReportNow(reportId).catch((e) => {
logger.error('[ProjectReport] Background send failed', reportId, ':', e && e.message ? e.message : String(e));
});
return res.status(202).json({
ok: true,
message: 'Report send started. The email will arrive in a few minutes.'
});
} catch (e) {
const msg = e && (e.message || String(e));
logger.error('POST /api/projects/reports/:reportId/send', reportId, ':', msg);
return res.status(500).json({
ok: false,
error: msg || 'Server error while sending report.',
code: 'REPORT_SEND_ERROR'
});
}
});
app.post('/api/projects', (req, res) => {
try {
const name = (req.body && req.body.name != null) ? String(req.body.name).trim() : 'Untitled project';
const owner = req.currentUser && req.currentUser.username ? req.currentUser.username : null;
const project = projectStore.createProject(name || 'Untitled project', owner);
if (!project) return res.status(400).json({ error: 'Failed to create project' });
res.json(project);
} catch (e) {
logger.error('POST /api/projects:', e.message);
res.status(500).json({ error: e.message });
}
});
function canAccessProject(user, project, level) {
if (!user || !project) return false;
if (user.role === 'admin') return true;
if (project.owner && project.owner === user.username) return true;
const shares = Array.isArray(project.shares) ? project.shares : [];
const share = shares.find((s) => s.username === user.username);
if (!share) return false;
if (level === 'view') return true;
if (level === 'edit') return share.access === 'admin' || share.access === 'user';
if (level === 'admin') return share.access === 'admin';
return false;
}
// Resolve the effective chat owner for channel-scoped requests.
// Returns the channelOwner string if the user is authorised, the user object
// for their own chat, or null if access is denied.
function resolveChannelUser(user, channelOwner) {
if (!user || !channelOwner || !chatStore.isChannelUsername(channelOwner)) return user;
if (channelOwner.startsWith('project_')) {
const pid = channelOwner.slice('project_'.length);
const project = projectStore.getProject(pid);
if (!project || !canAccessProject(user, project, 'view')) return null;
// Each user gets their own project chat: project_<id>_<username>
const uname = chatStore.safeUsername(typeof user === 'string' ? user : (user.username || ''));
return 'project_' + pid + '_' + uname;
}
const linkedOwner = channelLinks.getLinkedAppUser(channelOwner);
if (linkedOwner && typeof user !== 'string' && user.username === linkedOwner) return channelOwner;
// Other channel types (telegram_, discord_, matrix_, channel_) are system-level — admin only
if (typeof user !== 'string' && user.role === 'admin') return channelOwner;
return user;
}
app.get('/api/projects/:id', (req, res) => {
try {
const project = projectStore.getProject(req.params.id);
if (!project) return res.status(404).json({ error: 'Project not found' });
if (!canAccessProject(req.currentUser, project, 'view')) {
return res.status(403).json({ error: 'Forbidden' });
}
res.json(project);
} catch (e) {
logger.error('GET /api/projects/:id:', e.message);
res.status(500).json({ error: e.message });
}
});
app.put('/api/projects/:id', (req, res) => {
try {
const existing = projectStore.getProject(req.params.id);
if (!existing) return res.status(404).json({ error: 'Project not found' });
if (!canAccessProject(req.currentUser, existing, 'edit')) {
return res.status(403).json({ error: 'Forbidden' });
}
const updates = {};
if (req.body && req.body.name != null) {
const name = String(req.body.name).trim();
if (name) updates.name = name;
}
if (req.body && req.body.owner != null) {
if (req.currentUser.role !== 'admin') return res.status(403).json({ error: 'Only admins can transfer project ownership' });
const newOwner = String(req.body.owner).trim();
if (newOwner) updates.owner = newOwner;
}
const project = projectStore.updateProject(req.params.id, updates);
res.json(project);
} catch (e) {
logger.error('PUT /api/projects/:id:', e.message);
res.status(500).json({ error: e.message });
}
});
app.delete('/api/projects/:id', (req, res) => {
try {
const existing = projectStore.getProject(req.params.id);
if (!existing) return res.status(404).json({ error: 'Project not found' });
if (!canAccessProject(req.currentUser, existing, 'admin')) {
return res.status(403).json({ error: 'Forbidden' });
}
const ok = projectStore.deleteProject(req.params.id);
if (!ok) return res.status(404).json({ error: 'Project not found' });
res.json({ ok: true });
} catch (e) {
logger.error('DELETE /api/projects/:id:', e.message);
res.status(500).json({ error: e.message });
}
});
app.put('/api/projects/:id/shares', (req, res) => {
try {
const existing = projectStore.getProject(req.params.id);
if (!existing) return res.status(404).json({ error: 'Project not found' });
if (!canAccessProject(req.currentUser, existing, 'admin')) {
return res.status(403).json({ error: 'Forbidden' });
}
const shares = Array.isArray(req.body && req.body.shares) ? req.body.shares : [];
const project = projectStore.updateProject(req.params.id, { shares });
res.json(project);
} catch (e) {
logger.error('PUT /api/projects/:id/shares:', e.message);
res.status(500).json({ error: e.message });
}
});
app.get('/api/projects/:id/memory', (req, res) => {
try {
const project = projectStore.getProject(req.params.id);
if (!project) return res.status(404).json({ error: 'Project not found' });
if (!canAccessProject(req.currentUser, project, 'view')) return res.status(403).json({ error: 'Forbidden' });
res.json({ content: projectStore.readProjectMemory(req.params.id) });
} catch (e) {
logger.error('GET /api/projects/:id/memory:', e.message);
res.status(500).json({ error: e.message });
}
});
app.put('/api/projects/:id/memory', (req, res) => {
try {
const project = projectStore.getProject(req.params.id);
if (!project) return res.status(404).json({ error: 'Project not found' });
if (!canAccessProject(req.currentUser, project, 'edit')) return res.status(403).json({ error: 'Forbidden' });
projectStore.writeProjectMemory(req.params.id, req.body?.content ?? '');
res.json({ ok: true });
} catch (e) {
logger.error('PUT /api/projects/:id/memory:', e.message);
res.status(500).json({ error: e.message });
}
});
app.post('/api/projects/:id/memory/consolidate', (req, res) => {
try {
const project = projectStore.getProject(req.params.id);
if (!project) return res.status(404).json({ error: 'Project not found' });
if (!canAccessProject(req.currentUser, project, 'admin')) return res.status(403).json({ error: 'Forbidden' });
const raw = projectStore.readProjectMemory(req.params.id);
projectStore.writeProjectMemory(req.params.id, raw); // writeProjectMemory runs consolidation
const result = projectStore.readProjectMemory(req.params.id);
res.json({ ok: true, content: result });
} catch (e) {
logger.error('POST /api/projects/:id/memory/consolidate:', e.message);
res.status(500).json({ error: e.message });
}
});
app.post('/api/projects/:id/import', async (req, res) => {
try {
const projectId = req.params.id;
const project = projectStore.getProject(projectId);
if (!project) return res.status(404).json({ error: 'Project not found' });
if (!canAccessProject(req.currentUser, project, 'edit')) return res.status(403).json({ error: 'Forbidden' });
const type = (req.body && req.body.type) ? String(req.body.type).toLowerCase() : '';
const filename = (req.body && req.body.filename != null) ? String(req.body.filename).trim() : '';
const summarize = !!(req.body && req.body.summarize);
let result;
if (type === 'text') {
const text = req.body?.text != null ? String(req.body.text) : '';
result = projectImport.importText(projectId, text, req.body?.sectionTitle ? String(req.body.sectionTitle) : null);
if (!result.ok) return res.status(400).json({ error: result.error || 'Import failed' });
if (summarize && result.content) {
const summary = await projectImport.summarizeContent(result.content);
if (summary) {
const sectionTitle = filename ? `Summary: ${filename}` : 'Summary';
projectStore.appendProjectMemory(projectId, summary, sectionTitle);
}
return res.json({ ok: true, summary: summary || null });
}
return res.json({ ok: true });
}
if (type === 'pdf') {
const content = req.body?.content;
if (content == null) return res.status(400).json({ error: 'content (base64) required for PDF' });
const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content, 'base64');
result = await projectImport.importPdf(projectId, buffer, filename || 'document.pdf');
if (!result.ok) return res.status(400).json({ error: result.error || 'Import failed' });
if (summarize && result.content) {
const summary = await projectImport.summarizeContent(result.content);
if (summary) {
const sectionTitle = filename ? `Summary: ${filename}` : 'Summary';
projectStore.appendProjectMemory(projectId, summary, sectionTitle);
}
return res.json({ ok: true, chars: result.chars, summary: summary || null });
}
return res.json({ ok: true, chars: result.chars });
}
if (type === 'image') {
const content = req.body?.content;
if (content == null) return res.status(400).json({ error: 'content (base64 or data URL) required for image' });
result = await projectImport.importImage(projectId, content, filename || 'image');
if (!result.ok) return res.status(400).json({ error: result.error || 'Import failed' });
if (summarize && result.content) {
const summary = await projectImport.summarizeContent(result.content);
if (summary) {
const sectionTitle = filename ? `Summary: ${filename}` : 'Summary';
projectStore.appendProjectMemory(projectId, summary, sectionTitle);
}
return res.json({ ok: true, summary: summary || null });
}
return res.json({ ok: true });
}
if (type === 'docx') {
const content = req.body?.content;
if (content == null) return res.status(400).json({ error: 'content (base64) required for Word document' });
const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content, 'base64');
result = await projectImport.importDocx(projectId, buffer, filename || 'document.docx');
if (!result.ok) return res.status(400).json({ error: result.error || 'Import failed' });
if (summarize && result.content) {
const summary = await projectImport.summarizeContent(result.content);
if (summary) {
const sectionTitle = filename ? `Summary: ${filename}` : 'Summary';
projectStore.appendProjectMemory(projectId, summary, sectionTitle);
}
return res.json({ ok: true, chars: result.chars, summary: summary || null });
}
return res.json({ ok: true, chars: result.chars });
}
if (type === 'doc') {
const content = req.body?.content;
if (content == null) return res.status(400).json({ error: 'content (base64) required for Word .doc file' });
const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content, 'base64');
result = await projectImport.importDoc(projectId, buffer, filename || 'document.doc');
if (!result.ok) return res.status(400).json({ error: result.error || 'Import failed' });
if (summarize && result.content) {
const summary = await projectImport.summarizeContent(result.content);
if (summary) {
const sectionTitle = filename ? `Summary: ${filename}` : 'Summary';
projectStore.appendProjectMemory(projectId, summary, sectionTitle);
}
return res.json({ ok: true, chars: result.chars, summary: summary || null });
}
return res.json({ ok: true, chars: result.chars });
}
return res.status(400).json({ error: 'type must be text, pdf, image, doc, or docx' });
} catch (e) {
logger.error('POST /api/projects/:id/import:', e.message);
res.status(500).json({ error: e.message });
}
});
// ---------------------------------------------------------------------------
// Structured memory
// ---------------------------------------------------------------------------
app.get('/api/structured-memory', (req, res) => {
try {
const scopeUser = (req.currentUser && req.currentUser.username) || (req.session && req.session.user) || '';
res.json(structuredMemory.readAll(scopeUser));
} catch (e) {
logger.error('GET /api/structured-memory:', e.message);
res.status(500).json({ error: e.message });
}
});
app.put('/api/structured-memory', (req, res) => {
try {
const scopeUser = (req.currentUser && req.currentUser.username) || (req.session && req.session.user) || '';
structuredMemory.writeAll(req.body || {}, scopeUser);
res.json({ ok: true });
} catch (e) {
logger.error('PUT /api/structured-memory:', e.message);
res.status(500).json({ error: e.message });
}
});
// ---------------------------------------------------------------------------
// Skills
// ---------------------------------------------------------------------------
app.get('/api/skills', (req, res) => {
try {
skillsLib.ensureEnabledSkillsLoaded();
res.json({ skills: skillsLib.listSkills() });
} catch (e) {
logger.error('GET /api/skills:', e.message);
res.status(500).json({ error: e.message });
}
});
app.get('/api/skills/:id', (req, res) => {
try {
const meta = skillsLib.getSkillMeta(req.params.id);
const code = skillsLib.getSkillCode(req.params.id);
if (!meta) return res.status(404).json({ error: 'Skill not found' });
res.json({ id: req.params.id, name: meta.name, description: meta.description || '', code: code || '' });
} catch (e) {
logger.error('GET /api/skills/:id:', e.message);
res.status(500).json({ error: e.message });
}
});
app.put('/api/skills/:id', (req, res) => {
const { name, description, code } = req.body || {};
try {
const updates = {};
if (name !== undefined) updates.name = name;
if (description !== undefined) updates.description = description;
if (code !== undefined) updates.code = code;
const skill = skillsLib.updateSkill(req.params.id, updates);
res.json({ ok: true, skill });
} catch (e) {
logger.warn('PUT /api/skills/:id:', e.message);
res.status(400).json({ error: e.message });
}
});
app.put('/api/skills/:id/enabled', (req, res) => {
const enabled = req.body?.enabled === true;
try {
skillsLib.setSkillEnabled(req.params.id, enabled);
const enabledList = skillsLib.listSkills().filter(s => s.enabled).map(s => s.id);
updateConfig({ skills: { enabledIds: enabledList } });
res.json({ ok: true, enabled });
} catch (e) {
logger.warn('PUT /api/skills/:id/enabled:', e.message);
res.status(400).json({ error: e.message });
}
});
app.post('/api/skills/run', runLimiter, async (req, res) => {
const { id, args } = req.body || {};
if (!id) return res.status(400).json({ error: 'id required' });
try {
const result = await skillsLib.runSkill(id, args || {});
res.json({ ok: true, result });
} catch (e) {
logger.warn('POST /api/skills/run:', e.message);
res.status(500).json({ error: e.message });
}
});
app.delete('/api/skills/:id', (req, res) => {
const id = req.params.id;
const fs = require('fs');
const skillDir = skillsLib.getSkillDir(id);
if (!skillDir) return res.status(404).json({ error: 'Skill not found' });
try {
skillsLib.unloadSkill(id);
fs.rmSync(skillDir, { recursive: true });
res.json({ ok: true });
} catch (e) {
logger.error('DELETE /api/skills/:id:', e.message);
res.status(500).json({ error: e.message });
}
});
app.post('/api/skills/create', (req, res) => {
const { id, name, description, code } = req.body || {};
if (!id || typeof code !== 'string') {
return res.status(400).json({ error: 'id and code required' });
}
try {
const skill = skillsLib.createSkill(id, name, description, code);
res.json({ ok: true, skill });
} catch (e) {
logger.warn('POST /api/skills/create:', e.message);
res.status(400).json({ error: e.message });
}
});
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
app.get('/api/app-name', (req, res) => {
const c = getConfig();
const name = (c.ui && c.ui.appName != null && String(c.ui.appName).trim()) ? String(c.ui.appName).trim() : 'SHADOW_AI';
res.json({ appName: name });
});
// Upload / remove AI avatar (profile picture). Expects JSON { dataUrl } where
// dataUrl is a data:image/...;base64,... string. Only available to authenticated users.
app.post('/api/ui/avatar', (req, res) => {
try {
const body = req.body || {};
const dataUrl = typeof body.dataUrl === 'string' ? body.dataUrl.trim() : '';
if (!dataUrl) {
return res.status(400).json({ ok: false, error: 'dataUrl is required' });
}
const match = dataUrl.match(/^data:(image\/(png|jpeg|jpg|webp));base64,(.+)$/i);
if (!match) {
return res.status(400).json({ ok: false, error: 'dataUrl must be a base64-encoded PNG, JPEG, or WebP image.' });
}
const mime = match[1].toLowerCase();
let ext = match[2].toLowerCase();
if (ext === 'jpeg') ext = 'jpg';
const base64 = match[3];
const buf = Buffer.from(base64, 'base64');
if (!buf.length) {
return res.status(400).json({ ok: false, error: 'Image data is empty.' });
}
const fs = require('fs');
const DATA_DIR = path.join(__dirname, 'data');
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
const candidates = ['ai-avatar.png', 'ai-avatar.jpg', 'ai-avatar.jpeg', 'ai-avatar.webp'];
for (const name of candidates) {
const p = path.join(DATA_DIR, name);
if (fs.existsSync(p)) {
try { fs.unlinkSync(p); } catch (_) {}
}
}
const outPath = path.join(DATA_DIR, 'ai-avatar.' + ext);
fs.writeFileSync(outPath, buf);
logger.info('Updated AI avatar at', outPath, 'mime:', mime);
res.json({ ok: true });
} catch (e) {
logger.error('POST /api/ui/avatar:', e.message);
res.status(500).json({ ok: false, error: e.message });
}
});
// Users — lightweight username list for any authenticated user (used for share dropdowns)
app.get('/api/users/names', async (req, res) => {
try {
const users = await listUsers();
res.json({ usernames: users.map((u) => u.username) });
} catch (e) {
logger.error('GET /api/users/names:', e.message);
res.status(500).json({ error: e.message });
}
});
// Users (admin only)
app.get('/api/users', async (req, res) => {
if (!requireAdmin(req, res)) return;
try {
const users = await listUsers();
res.json({ ok: true, users });
} catch (e) {
logger.error('GET /api/users:', e.message);
res.status(500).json({ ok: false, error: e.message });
}
});
app.post('/api/users', async (req, res) => {
if (!requireAdmin(req, res)) return;
try {
const body = req.body || {};
const user = await createUser({
username: body.username,
password: body.password,
role: body.role
});
res.json({ ok: true, user });
} catch (e) {
logger.error('POST /api/users:', e.message);
res.status(400).json({ ok: false, error: e.message });
}
});
app.put('/api/users/:username', async (req, res) => {
if (!requireAdmin(req, res)) return;
try {
const updates = {};
if (req.body && typeof req.body.password === 'string' && req.body.password) {
updates.password = req.body.password;
}
if (req.body && typeof req.body.role === 'string') {
updates.role = req.body.role;
}
await updateUser(req.params.username, updates);
res.json({ ok: true });
} catch (e) {
logger.error('PUT /api/users/:username:', e.message);
res.status(400).json({ ok: false, error: e.message });
}
});
app.delete('/api/users/:username', async (req, res) => {
if (!requireAdmin(req, res)) return;
try {
await deleteUser(req.params.username);
res.json({ ok: true });
} catch (e) {
logger.error('DELETE /api/users/:username:', e.message);
res.status(400).json({ ok: false, error: e.message });
}
});
app.delete('/api/ui/avatar', (req, res) => {
try {
const fs = require('fs');
const DATA_DIR = path.join(__dirname, 'data');
const candidates = ['ai-avatar.png', 'ai-avatar.jpg', 'ai-avatar.jpeg', 'ai-avatar.webp'];
let removed = false;
for (const name of candidates) {
const p = path.join(DATA_DIR, name);
if (fs.existsSync(p)) {
try { fs.unlinkSync(p); removed = true; } catch (_) {}
}
}
if (removed) {
logger.info('Removed AI avatar');
}
res.json({ ok: true });
} catch (e) {
logger.error('DELETE /api/ui/avatar:', e.message);
res.status(500).json({ ok: false, error: e.message });
}
});
app.get('/api/config', (req, res) => {
if (!requireAdmin(req, res)) return;
const c = getConfig();
// Never expose credentials — strip passwordHash and email.auth.pass
res.json({
server: c.server,
timezone: c.timezone || '',
auth: { username: c.auth.username },