Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
493 lines (430 loc) · 16.2 KB
/
Copy pathserver.ts
File metadata and controls
493 lines (430 loc) · 16.2 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
import express, { Request, Response, NextFunction } from 'express';
import path from 'path';
import fs from 'fs';
import crypto from 'crypto';
import { createServer as createViteServer } from 'vite';
import { askCopilot } from './server/copilotService';
// Admin persistent settings file location
const SETTINGS_FILE_PATH = path.join(process.cwd(), 'server', 'admin_settings.json');
// Constant-time scrypt PIN hashing helpers
function hashPin(pin: string): string {
const salt = crypto.randomBytes(16).toString('hex');
const derivedKey = crypto.scryptSync(pin, salt, 64);
return `${salt}:${derivedKey.toString('hex')}`;
}
function verifyPin(pin: string, storedHash: string): boolean {
try {
const [salt, key] = storedHash.split(':');
if (!salt || !key) return false;
const keyBuffer = Buffer.from(key, 'hex');
const derivedKey = crypto.scryptSync(pin, salt, keyBuffer.length);
if (keyBuffer.length !== derivedKey.length) {
return false;
}
return crypto.timingSafeEqual(keyBuffer, derivedKey);
} catch {
return false;
}
}
// 1. Initialize admin PIN from process.env.ADMIN_PIN
const envAdminPin = (process.env.ADMIN_PIN || '').trim();
const isProduction = process.env.NODE_ENV === 'production';
let currentAdminPinHash = '';
if (envAdminPin) {
currentAdminPinHash = hashPin(envAdminPin);
} else if (isProduction) {
console.error('FATAL: ADMIN_PIN environment variable is required in production mode.');
process.exit(1);
} else {
// Generate random 6-digit PIN in development
const devGeneratedPin = crypto.randomInt(100000, 999999).toString();
currentAdminPinHash = hashPin(devGeneratedPin);
console.warn('====================================================');
console.warn('[Security Warning] ADMIN_PIN is not set in environment.');
console.warn(`[Security Warning] Generated random development ADMIN_PIN: ${devGeneratedPin}`);
console.warn('====================================================');
}
const DEFAULT_SERVER_ADMIN_SETTINGS = {
announcement: {
enabled: true,
title: 'عضو کانال تلگرام ما باشید',
description: 'برای دریافت آخرین آپدیتها، ترفندهای هوش مصنوعی و ارتباط مستقیم با ما، به کانال تلگرام بپیوندید.',
buttonText: 'عضویت در کانال',
buttonUrl: 'https://t.me/ChatiPatiApp',
theme: 'telegram',
icon: 'telegram',
showCloseButton: true,
allowDismiss: true,
dismissDuration: '24h',
placement: 'all',
pulseAnimation: true,
version: 1,
},
copilotMode: 'smart',
customNotice: '',
maintenanceMode: false,
updatedAt: Date.now(),
adminPinHash: currentAdminPinHash,
};
let serverAdminSettings = { ...DEFAULT_SERVER_ADMIN_SETTINGS };
// Load settings from disk if available
try {
if (fs.existsSync(SETTINGS_FILE_PATH)) {
const raw = fs.readFileSync(SETTINGS_FILE_PATH, 'utf-8');
const parsed = JSON.parse(raw);
// Strictly purge legacy plain-text adminPin if present
delete (parsed as any).adminPin;
// If an updated hash was saved and no env override exists, respect it
if (!envAdminPin && parsed.adminPinHash && typeof parsed.adminPinHash === 'string') {
currentAdminPinHash = parsed.adminPinHash;
}
serverAdminSettings = {
...DEFAULT_SERVER_ADMIN_SETTINGS,
...parsed,
adminPinHash: currentAdminPinHash,
announcement: {
...DEFAULT_SERVER_ADMIN_SETTINGS.announcement,
...(parsed.announcement || {}),
},
};
}
} catch (e) {
console.warn('Could not read admin_settings.json, using defaults', e);
}
function saveAdminSettingsToDisk(): void {
try {
const dir = path.dirname(SETTINGS_FILE_PATH);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Never save raw adminPin
const safeSettings: any = {
announcement: serverAdminSettings.announcement,
copilotMode: serverAdminSettings.copilotMode,
customNotice: serverAdminSettings.customNotice,
maintenanceMode: serverAdminSettings.maintenanceMode,
updatedAt: serverAdminSettings.updatedAt,
adminPinHash: currentAdminPinHash,
};
fs.writeFileSync(SETTINGS_FILE_PATH, JSON.stringify(safeSettings, null, 2), 'utf-8');
} catch (err) {
console.error('Failed to write admin_settings.json:', err);
}
}
// Admin Sessions (32-byte random token, 2 hours expiration)
interface AdminSession {
token: string;
createdAt: number;
expiresAt: number;
}
const adminSessions = new Map<string, AdminSession>();
const ADMIN_SESSION_TTL_MS = 2 * 60 * 60 * 1000; // 2 hours
function cleanupExpiredAdminSessions(): void {
const now = Date.now();
for (const [tok, sess] of adminSessions.entries()) {
if (now > sess.expiresAt) {
adminSessions.delete(tok);
}
}
}
// Middleware: Require valid Admin session token
function requireAdmin(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
res.status(401).json({ error: 'دسترسی غیرمجاز: نیاز به توکن مدیریت است' });
return;
}
const token = authHeader.slice(7).trim();
const session = adminSessions.get(token);
const now = Date.now();
if (!session || now > session.expiresAt) {
if (session) {
adminSessions.delete(token);
}
res.status(401).json({ error: 'نشست منقضی شده یا نامعتبر است. لطفاً مجدداً وارد شوید' });
return;
}
next();
}
// Simple in-memory rate limiter per IP
interface RateLimitRecord {
count: number;
resetTime: number;
}
const rateLimitMap = new Map<string, RateLimitRecord>();
function apiRateLimiter(maxRequests: number = 60, windowMs: number = 60000) {
return (req: Request, res: Response, next: NextFunction) => {
const ip = req.ip || req.socket.remoteAddress || 'unknown';
const now = Date.now();
const record = rateLimitMap.get(ip);
if (!record || now > record.resetTime) {
rateLimitMap.set(ip, { count: 1, resetTime: now + windowMs });
return next();
}
if (record.count >= maxRequests) {
res.status(429).json({
error: 'Too many requests, please slow down.',
retryAfterMs: record.resetTime - now,
});
return;
}
record.count += 1;
return next();
};
}
async function startServer() {
const app = express();
const PORT = Number(process.env.PORT) || 3000;
// Basic security and parsing middleware
app.set('trust proxy', 1);
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
// Basic security headers
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('X-XSS-Protection', '1; mode=block');
next();
});
// Strict rate limiter for Admin Login: max 5 requests per 5 minutes per IP
const adminLoginRateLimiter = apiRateLimiter(5, 5 * 60 * 1000);
// Health check endpoint
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
runtime: 'Dorsa Brain & Multi-Stage Companion Engine',
environment: process.env.NODE_ENV || 'development',
time: new Date().toISOString(),
});
});
// Admin Settings Public Endpoint (Never returns adminPin or adminPinHash)
app.get('/api/admin/settings', (req, res) => {
res.json({
announcement: serverAdminSettings.announcement,
copilotMode: serverAdminSettings.copilotMode,
customNotice: serverAdminSettings.customNotice,
maintenanceMode: serverAdminSettings.maintenanceMode,
updatedAt: serverAdminSettings.updatedAt,
});
});
// Admin Login Endpoint (constant-time verification, returns 32-byte session token)
app.post('/api/admin/login', adminLoginRateLimiter, (req: Request, res: Response) => {
const { pin } = req.body;
if (!pin || typeof pin !== 'string') {
res.status(400).json({ error: 'PIN is required' });
return;
}
cleanupExpiredAdminSessions();
const isValid = verifyPin(pin.trim(), currentAdminPinHash);
if (!isValid) {
res.status(401).json({ error: 'رمز عبور ادمین نادرست است' });
return;
}
const token = crypto.randomBytes(32).toString('hex');
const now = Date.now();
const expiresAt = now + ADMIN_SESSION_TTL_MS;
adminSessions.set(token, {
token,
createdAt: now,
expiresAt,
});
res.json({
success: true,
token,
expiresAt,
message: 'Authentication successful',
});
});
// Admin Settings Update Endpoint (Protected by requireAdmin)
app.post('/api/admin/settings', requireAdmin, (req: Request, res: Response) => {
try {
const { announcement, copilotMode, customNotice, maintenanceMode, adminPin } = req.body;
// Handle secure PIN update if provided
if (adminPin && typeof adminPin === 'string') {
const trimmedPin = adminPin.trim();
if (trimmedPin.length < 4 || trimmedPin.length > 32) {
res.status(400).json({ error: 'رمز عبور ادمین باید بین ۴ تا ۳۲ کاراکتر باشد' });
return;
}
currentAdminPinHash = hashPin(trimmedPin);
serverAdminSettings.adminPinHash = currentAdminPinHash;
}
// Validate announcement banner
if (announcement && typeof announcement === 'object') {
let {
enabled,
title,
description,
buttonText,
buttonUrl,
theme,
icon,
showCloseButton,
allowDismiss,
dismissDuration,
placement,
pulseAnimation,
} = announcement;
// Sanitize string lengths
if (typeof title === 'string') {
title = title.trim().slice(0, 150);
} else {
title = serverAdminSettings.announcement.title;
}
if (typeof description === 'string') {
description = description.trim().slice(0, 500);
} else {
description = serverAdminSettings.announcement.description;
}
if (typeof buttonText === 'string') {
buttonText = buttonText.trim().slice(0, 60);
} else {
buttonText = serverAdminSettings.announcement.buttonText;
}
// Validate buttonUrl: strictly enforce https only
if (typeof buttonUrl === 'string' && buttonUrl.trim().length > 0) {
const trimmedUrl = buttonUrl.trim();
if (trimmedUrl.length > 500) {
res.status(400).json({ error: 'آدرس دکمه اعلان نباید بیشتر از ۵۰۰ کاراکتر باشد' });
return;
}
try {
const parsedUrl = new URL(trimmedUrl);
if (parsedUrl.protocol !== 'https:') {
res.status(400).json({ error: 'آدرس اینترنتی دکمه حتماً باید با پروتکل امن https باشد' });
return;
}
buttonUrl = trimmedUrl;
} catch {
res.status(400).json({ error: 'فرمت آدرس اینترنتی دکمه نامعتبر است' });
return;
}
} else {
buttonUrl = '';
}
serverAdminSettings.announcement = {
...serverAdminSettings.announcement,
enabled: typeof enabled === 'boolean' ? enabled : serverAdminSettings.announcement.enabled,
title,
description,
buttonText,
buttonUrl,
theme: theme || serverAdminSettings.announcement.theme,
icon: icon || serverAdminSettings.announcement.icon,
showCloseButton: typeof showCloseButton === 'boolean' ? showCloseButton : serverAdminSettings.announcement.showCloseButton,
allowDismiss: typeof allowDismiss === 'boolean' ? allowDismiss : serverAdminSettings.announcement.allowDismiss,
dismissDuration: dismissDuration || serverAdminSettings.announcement.dismissDuration,
placement: placement || serverAdminSettings.announcement.placement,
pulseAnimation: typeof pulseAnimation === 'boolean' ? pulseAnimation : serverAdminSettings.announcement.pulseAnimation,
version: (serverAdminSettings.announcement.version || 1) + 1,
};
}
if (copilotMode && ['smart', 'fast', 'creative'].includes(copilotMode)) {
serverAdminSettings.copilotMode = copilotMode;
}
if (typeof customNotice === 'string') {
serverAdminSettings.customNotice = customNotice.slice(0, 1000);
}
if (typeof maintenanceMode === 'boolean') {
serverAdminSettings.maintenanceMode = maintenanceMode;
}
serverAdminSettings.updatedAt = Date.now();
saveAdminSettingsToDisk();
// Return sanitized settings (never returning pin or pin hash)
res.json({
success: true,
settings: {
announcement: serverAdminSettings.announcement,
copilotMode: serverAdminSettings.copilotMode,
customNotice: serverAdminSettings.customNotice,
maintenanceMode: serverAdminSettings.maintenanceMode,
updatedAt: serverAdminSettings.updatedAt,
},
});
} catch (err: any) {
console.error('Error saving admin settings:', err);
res.status(500).json({ error: 'Failed to update admin settings' });
}
});
// Copilot proxy endpoint for text chat
app.post('/api/copilot/chat', apiRateLimiter(45, 60000), async (req: Request, res: Response) => {
try {
const { prompt, mode } = req.body;
if (!prompt || typeof prompt !== 'string' || prompt.trim().length === 0) {
res.status(400).json({ error: 'Valid prompt string is required' });
return;
}
const copilotResponse = await askCopilot(prompt, null, mode || 'smart');
if (copilotResponse) {
res.json({ text: copilotResponse, source: 'copilot' });
return;
}
// If Copilot network call returns null, return fallback
res.json({
text: null,
source: 'fallback',
});
} catch (err: any) {
console.error('API /api/copilot/chat error:', err);
res.status(500).json({ error: 'Internal server error processing chat' });
}
});
// Copilot proxy endpoint for image understanding (Vision)
app.post('/api/copilot/image', apiRateLimiter(30, 60000), async (req: Request, res: Response) => {
try {
const { prompt, imageBase64, mode } = req.body;
if (!prompt || typeof prompt !== 'string' || prompt.trim().length === 0) {
res.status(400).json({ error: 'Valid prompt string is required' });
return;
}
let imageBuffer: Buffer | null = null;
if (imageBase64 && typeof imageBase64 === 'string') {
let base64Data = imageBase64;
if (imageBase64.includes(',')) {
base64Data = imageBase64.split(',')[1];
}
imageBuffer = Buffer.from(base64Data.trim(), 'base64');
}
const copilotResponse = await askCopilot(prompt, imageBuffer, mode || 'smart');
if (copilotResponse) {
res.json({ text: copilotResponse, source: 'copilot' });
return;
}
res.json({
text: null,
source: 'fallback',
});
} catch (err: any) {
console.error('API /api/copilot/image error:', err);
res.status(500).json({ error: 'Internal server error processing image' });
}
});
// Vite middleware for development vs static build serving for production
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req: Request, res: Response) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
// Global Error Handler
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
console.error('Unhandled server error:', err);
if (!res.headersSent) {
res.status(500).json({ error: 'An unexpected error occurred' });
}
});
app.listen(PORT, '0.0.0.0', () => {
console.log(`Dorsa Server running on http://0.0.0.0:${PORT}`);
});
}
startServer().catch((err) => {
console.error('Failed to start Dorsa server:', err);
process.exit(1);
});