-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1545 lines (1334 loc) · 51.8 KB
/
server.js
File metadata and controls
1545 lines (1334 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import "dotenv/config";
import express from "express";
import cors from "cors";
import helmet from "helmet";
import compression from "compression";
import rateLimit from "express-rate-limit";
import path from "path";
import crypto from "crypto";
import fs from "fs";
import { fileURLToPath } from "url";
import { existsSync as fsExists, mkdirSync, readdirSync, statSync, unlinkSync, readFileSync, writeFileSync, appendFileSync } from "fs";
import multer from "multer";
import {
getAuthUrl, exchangeCode, getToken, removeToken, loadTokens,
postContent, postComment, likePost, getValidToken,
} from "./platforms.js";
import {
parseContentToSlides, renderVideo, getCompositionId,
formatToVideoType, platformToAspectRatio,
} from "./video/render.js";
import {
generateImage, generateAIVideo, generateFullMedia, buildImagePrompt,
} from "./ai-media.js";
import {
schedulePost, cancelJob, scheduleRecurring, stopRecurring, getSchedulerStatus, addLog, loadLog,
} from "./scheduler.js";
import {
registerUser, loginUser, verifyToken, authMiddleware, optionalAuth,
requirePlan, checkPostLimit, checkPlatformLimit, incrementPostCount,
upgradePlan, findUserByLemonCustomerId, findUserByEmail, PLANS,
} from "./auth.js";
import {
getDb, dbHealthCheck, closeDb,
dbGetAllPosts, dbGetPostById, dbGetPostsByStatus,
dbInsertPost, dbUpdatePost, dbDeletePost,
} from "./db.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const OUTPUT_DIR = path.join(__dirname, "output");
const UPLOADS_DIR = path.join(__dirname, "uploads");
const ERRORS_LOG = path.join(__dirname, "errors.log");
if (!fsExists(OUTPUT_DIR)) mkdirSync(OUTPUT_DIR, { recursive: true });
if (!fsExists(UPLOADS_DIR)) mkdirSync(UPLOADS_DIR, { recursive: true });
const isProduction = process.env.NODE_ENV === "production";
const PORT = process.env.PORT || 3001;
const BACKEND_URL = process.env.BACKEND_URL || `http://localhost:${PORT}`;
// Initialize database on startup
getDb();
const app = express();
// === HTTPS ENFORCEMENT (production) ===
if (isProduction) {
app.use((req, res, next) => {
// Trust proxy headers (Railway, Render, Docker behind reverse proxy)
if (req.headers["x-forwarded-proto"] && req.headers["x-forwarded-proto"] !== "https") {
return res.redirect(301, `https://${req.headers.host}${req.url}`);
}
next();
});
}
// Security headers
app.use(helmet({
contentSecurityPolicy: false, // CSP handled by frontend framework
crossOriginEmbedderPolicy: false, // allow loading external images/videos
hsts: isProduction ? {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true,
} : false,
}));
// Gzip compression
app.use(compression());
// CORS: restricted in production, open in dev
app.use(cors(isProduction ? { origin: process.env.APP_URL || false } : undefined));
app.use(express.json({ limit: "1mb" }));
// Trust proxy for rate limiting behind reverse proxy
app.set("trust proxy", 1);
// === RATE LIMITING ===
// Auth routes: strict (5 attempts per 15 minutes)
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Zu viele Anmeldeversuche. Bitte warte 15 Minuten." },
keyGenerator: (req) => req.ip,
});
// AI generation routes: moderate (20 per minute)
const aiLimiter = rateLimit({
windowMs: 60 * 1000,
max: 20,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Zu viele AI-Anfragen. Bitte warte kurz." },
keyGenerator: (req) => req.ip,
});
// General API: loose (100 per minute)
const generalLimiter = rateLimit({
windowMs: 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Zu viele Anfragen. Bitte warte kurz." },
keyGenerator: (req) => req.ip,
});
// Apply general rate limit to all API routes
app.use("/api/", generalLimiter);
// === INPUT VALIDATION HELPERS ===
function validateString(value, fieldName, { minLength = 0, maxLength = 10000, required = false } = {}) {
if (value === undefined || value === null) {
if (required) throw new Error(`${fieldName} ist erforderlich`);
return value;
}
if (typeof value !== "string") throw new Error(`${fieldName} muss ein String sein`);
if (value.length < minLength) throw new Error(`${fieldName} muss mindestens ${minLength} Zeichen haben`);
if (value.length > maxLength) throw new Error(`${fieldName} darf maximal ${maxLength} Zeichen haben`);
return value;
}
function validateArray(value, fieldName, { maxItems = 100 } = {}) {
if (value === undefined || value === null) return value;
if (!Array.isArray(value)) throw new Error(`${fieldName} muss ein Array sein`);
if (value.length > maxItems) throw new Error(`${fieldName} darf maximal ${maxItems} Eintraege haben`);
return value;
}
function sanitizeHtml(str) {
if (typeof str !== "string") return str;
return str.replace(/[<>]/g, "");
}
// === AUTH ROUTES ===
app.post("/api/auth/register", authLimiter, async (req, res) => {
try {
const { email, password, name } = req.body;
validateString(email, "email", { required: true, maxLength: 255 });
validateString(password, "password", { required: true, minLength: 8, maxLength: 128 });
validateString(name, "name", { maxLength: 100 });
const result = await registerUser(email, password, name ? sanitizeHtml(name) : name);
res.json(result);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.post("/api/auth/login", authLimiter, async (req, res) => {
try {
const { email, password } = req.body;
validateString(email, "email", { required: true, maxLength: 255 });
validateString(password, "password", { required: true, maxLength: 128 });
const result = await loginUser(email, password);
res.json(result);
} catch (err) {
res.status(401).json({ error: err.message });
}
});
app.get("/api/auth/me", authMiddleware, (req, res) => {
const { passwordHash, ...safe } = req.user;
const plan = PLANS[req.user.plan || "free"];
res.json({ ...safe, planDetails: plan });
});
app.get("/api/plans", (_req, res) => {
res.json(PLANS);
});
// === LEMONSQUEEZY WEBHOOK ===
// Set LEMON_WEBHOOK_SECRET in .env
// In Lemonsqueezy: Webhook URL = https://your-domain.com/api/webhooks/lemonsqueezy
app.post("/api/webhooks/lemonsqueezy", express.raw({ type: "application/json" }), (req, res) => {
const secret = process.env.LEMON_WEBHOOK_SECRET;
// Verify signature if secret is set
if (secret) {
const sig = req.headers["x-signature"];
if (!sig) return res.status(401).json({ error: "Missing signature" });
const hmac = crypto.createHmac("sha256", secret)
.update(typeof req.body === "string" ? req.body : JSON.stringify(req.body))
.digest("hex");
if (hmac !== sig) return res.status(401).json({ error: "Invalid signature" });
}
try {
const event = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
const eventName = event.meta?.event_name;
const attrs = event.data?.attributes;
const email = attrs?.user_email;
const customerId = String(attrs?.customer_id || "");
const subscriptionId = String(event.data?.id || "");
const variantName = attrs?.variant_name?.toLowerCase() || attrs?.product_name?.toLowerCase() || "";
// Map variant/product name to plan
let plan = "starter";
if (variantName.includes("pro")) plan = "pro";
if (variantName.includes("business")) plan = "business";
console.log(`[Lemon] ${eventName} -- ${email} -> ${plan}`);
if (eventName === "subscription_created" || eventName === "subscription_updated" || eventName === "subscription_resumed") {
const user = findUserByEmail(email) || findUserByLemonCustomerId(customerId);
if (user) {
upgradePlan(user.id, plan, {
customerId,
subscriptionId,
expiresAt: attrs?.renews_at || null,
});
console.log(`[Lemon] Upgraded ${email} to ${plan}`);
} else {
console.warn(`[Lemon] User not found: ${email}`);
}
}
if (eventName === "subscription_cancelled" || eventName === "subscription_expired") {
const user = findUserByEmail(email) || findUserByLemonCustomerId(customerId);
if (user) {
upgradePlan(user.id, "free", { customerId, subscriptionId });
console.log(`[Lemon] Downgraded ${email} to free`);
}
}
// order_created -- for one-time payments
if (eventName === "order_created") {
const user = findUserByEmail(email) || findUserByLemonCustomerId(customerId);
if (user) {
upgradePlan(user.id, plan, { customerId });
console.log(`[Lemon] Order: ${email} -> ${plan}`);
}
}
res.json({ received: true });
} catch (err) {
console.error("[Lemon] Webhook error:", err.message);
res.status(400).json({ error: err.message });
}
});
// --- Security: Rate limiting (in-memory, per-key) ---
const rateLimits = new Map();
function rateLimitCustom(key, maxPerMinute = 30) {
const now = Date.now();
const window = 60_000;
const hits = rateLimits.get(key) || [];
const recent = hits.filter(t => now - t < window);
if (recent.length >= maxPerMinute) return false;
recent.push(now);
rateLimits.set(key, recent);
return true;
}
// --- Security: Daily AI call budget (per-IP, resets at midnight) ---
const aiBudgets = new Map();
const AI_DAILY_LIMIT = parseInt(process.env.AI_DAILY_LIMIT, 10) || 100; // default 100 AI calls/day
function checkAIBudget(ip) {
const today = new Date().toISOString().slice(0, 10); // "YYYY-MM-DD"
const key = `${ip}:${today}`;
const used = aiBudgets.get(key) || 0;
if (used >= AI_DAILY_LIMIT) return false;
aiBudgets.set(key, used + 1);
// Cleanup old entries once a day
for (const [k] of aiBudgets) {
if (!k.endsWith(today)) aiBudgets.delete(k);
}
return true;
}
function getAIBudgetRemaining(ip) {
const today = new Date().toISOString().slice(0, 10);
const used = aiBudgets.get(`${ip}:${today}`) || 0;
return { used, limit: AI_DAILY_LIMIT, remaining: AI_DAILY_LIMIT - used };
}
// --- BYOK (Bring Your Own Key) support ---
// Users can send their own API keys via headers to bypass server budget limits
function extractUserKeys(req) {
return {
anthropic: req.headers["x-user-anthropic-key"] || null,
openai: req.headers["x-user-openai-key"] || null,
stability: req.headers["x-user-stability-key"] || null,
fal: req.headers["x-user-fal-key"] || null,
replicate: req.headers["x-user-replicate-key"] || null,
};
}
function getApiKey(provider, userKeys) {
const envMap = {
anthropic: "ANTHROPIC_API_KEY",
openai: "OPENAI_API_KEY",
stability: "STABILITY_API_KEY",
fal: "FAL_KEY",
replicate: "REPLICATE_API_TOKEN",
};
return (userKeys && userKeys[provider]) || process.env[envMap[provider]] || null;
}
function isByok(userKeys) {
return userKeys && Object.values(userKeys).some(k => !!k);
}
// --- Security: Webhook authentication ---
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || null;
function webhookAuth(req, res, next) {
if (!WEBHOOK_SECRET) return next(); // no secret = no protection (dev mode)
const provided = req.headers["x-webhook-secret"] || req.query.secret;
if (provided !== WEBHOOK_SECRET) {
return res.status(401).json({ error: "Ungueltiger Webhook-Secret. Setze x-webhook-secret Header." });
}
next();
}
// --- Secure File Upload ---
const ALLOWED_MIME_TYPES = new Set([
"image/jpeg", "image/png", "image/gif", "image/webp", "image/svg+xml",
"video/mp4", "video/webm", "video/quicktime",
"audio/mpeg", "audio/wav", "audio/ogg", "audio/mp4", "audio/webm",
]);
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
const upload = multer({
storage: multer.diskStorage({
destination: (_req, _file, cb) => cb(null, UPLOADS_DIR),
filename: (_req, file, cb) => {
// Sanitize: strip path separators, use crypto ID + safe extension
const ext = path.extname(file.originalname).toLowerCase().replace(/[^a-z0-9.]/g, "");
const safeExts = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".mp4", ".webm", ".mov", ".mp3", ".wav", ".ogg", ".m4a"];
const finalExt = safeExts.includes(ext) ? ext : "";
cb(null, `${crypto.randomUUID()}${finalExt}`);
},
}),
limits: { fileSize: MAX_FILE_SIZE },
fileFilter: (_req, file, cb) => {
if (!ALLOWED_MIME_TYPES.has(file.mimetype)) {
return cb(new Error(`Dateityp nicht erlaubt: ${file.mimetype}`));
}
cb(null, true);
},
});
// Serve uploaded files
app.use("/uploads", express.static(UPLOADS_DIR));
// === MEDIA UPLOAD & LIBRARY ===
// Upload files (max 5 at once)
app.post("/api/media/upload", (req, res) => {
if (!rateLimitCustom(req.ip, 60)) return res.status(429).json({ error: "Zu viele Uploads. Bitte warte kurz." });
upload.array("files", 5)(req, res, (err) => {
if (err instanceof multer.MulterError) {
if (err.code === "LIMIT_FILE_SIZE") return res.status(413).json({ error: "Datei zu gross (max 100MB)" });
return res.status(400).json({ error: err.message });
}
if (err) return res.status(400).json({ error: err.message });
if (!req.files || req.files.length === 0) return res.status(400).json({ error: "Keine Dateien hochgeladen" });
const uploaded = req.files.map(f => ({
id: path.basename(f.filename, path.extname(f.filename)),
filename: f.filename,
originalName: f.originalname.replace(/[<>:"/\\|?*]/g, "_"), // sanitize for display
mimetype: f.mimetype,
size: f.size,
type: f.mimetype.startsWith("image/") ? "image" : f.mimetype.startsWith("video/") ? "video" : "audio",
url: `/uploads/${f.filename}`,
uploadedAt: new Date().toISOString(),
}));
res.json({ success: true, files: uploaded });
});
});
// List all uploaded media
app.get("/api/media/library", (_req, res) => {
try {
const files = readdirSync(UPLOADS_DIR)
.filter(f => !f.startsWith("."))
.map(f => {
const stat = statSync(path.join(UPLOADS_DIR, f));
const ext = path.extname(f).toLowerCase();
const imageExts = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"];
const videoExts = [".mp4", ".webm", ".mov"];
const type = imageExts.includes(ext) ? "image" : videoExts.includes(ext) ? "video" : "audio";
return {
id: path.basename(f, ext),
filename: f,
type,
size: stat.size,
url: `/uploads/${f}`,
uploadedAt: stat.birthtime.toISOString(),
};
})
.sort((a, b) => new Date(b.uploadedAt) - new Date(a.uploadedAt));
res.json({ files });
} catch {
res.json({ files: [] });
}
});
// Delete a media file
app.delete("/api/media/:filename", (req, res) => {
const filename = path.basename(req.params.filename); // prevent path traversal
const filePath = path.join(UPLOADS_DIR, filename);
// Double-check: resolved path must be inside UPLOADS_DIR
if (!path.resolve(filePath).startsWith(path.resolve(UPLOADS_DIR))) {
return res.status(403).json({ error: "Zugriff verweigert" });
}
if (!fsExists(filePath)) return res.status(404).json({ error: "Datei nicht gefunden" });
try {
unlinkSync(filePath);
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// === POST MANAGEMENT (SQLite-backed) ===
// Create a new post
app.post("/api/posts", optionalAuth, (req, res) => {
if (!rateLimitCustom(req.ip, 30)) return res.status(429).json({ error: "Rate limit" });
try {
const { text, media, platforms, scheduledAt, tags } = req.body;
if (!text && (!media || media.length === 0)) {
return res.status(400).json({ error: "Text oder Medien erforderlich" });
}
// Validate inputs
validateString(text, "text", { maxLength: 10000 });
validateArray(media, "media", { maxItems: 10 });
validateArray(platforms, "platforms", { maxItems: 10 });
validateArray(tags, "tags", { maxItems: 20 });
// Validate media references exist
if (media && Array.isArray(media)) {
for (const m of media) {
const safeName = path.basename(m.filename || "");
const filePath = path.join(UPLOADS_DIR, safeName);
if (!fsExists(filePath)) {
return res.status(400).json({ error: `Mediendatei nicht gefunden: ${safeName}` });
}
}
}
const post = {
id: crypto.randomUUID(),
text: sanitizeHtml(text || ""),
media: (media || []).map(m => ({
...m,
filename: path.basename(m.filename || ""), // sanitize
})),
platforms: platforms || [],
tags: tags || [],
status: scheduledAt ? "scheduled" : "draft",
scheduledAt: scheduledAt || null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
postedAt: null,
postResults: null,
};
dbInsertPost(post);
// If scheduled, register with scheduler
if (scheduledAt) {
schedulePost({
id: `post-${post.id}`,
content: post.text,
platforms: post.platforms,
scheduledAt,
});
}
res.json({ success: true, post });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// Get all posts (with optional status filter)
app.get("/api/posts", (req, res) => {
const { status } = req.query;
const posts = status ? dbGetPostsByStatus(status) : dbGetAllPosts();
res.json({ posts });
});
// Get a single post
app.get("/api/posts/:id", (req, res) => {
const post = dbGetPostById(req.params.id);
if (!post) return res.status(404).json({ error: "Post nicht gefunden" });
res.json(post);
});
// Update a post
app.put("/api/posts/:id", (req, res) => {
try {
const post = dbGetPostById(req.params.id);
if (!post) return res.status(404).json({ error: "Post nicht gefunden" });
if (post.status === "posted") return res.status(400).json({ error: "Bereits gepostete Posts koennen nicht bearbeitet werden" });
const { text, media, platforms, scheduledAt, tags, status } = req.body;
const updates = { updatedAt: new Date().toISOString() };
if (text !== undefined) { validateString(text, "text", { maxLength: 10000 }); updates.text = sanitizeHtml(text); }
if (media !== undefined) { validateArray(media, "media", { maxItems: 10 }); updates.media = media.map(m => ({ ...m, filename: path.basename(m.filename || "") })); }
if (platforms !== undefined) { validateArray(platforms, "platforms", { maxItems: 10 }); updates.platforms = platforms; }
if (tags !== undefined) { validateArray(tags, "tags", { maxItems: 20 }); updates.tags = tags; }
if (status && ["draft", "scheduled"].includes(status)) updates.status = status;
if (scheduledAt !== undefined) {
updates.scheduledAt = scheduledAt;
if (scheduledAt) {
updates.status = "scheduled";
cancelJob(`post-${post.id}`);
schedulePost({
id: `post-${post.id}`,
content: updates.text || post.text,
platforms: updates.platforms || post.platforms,
scheduledAt,
});
} else {
updates.status = "draft";
cancelJob(`post-${post.id}`);
}
}
dbUpdatePost(req.params.id, updates);
const updatedPost = dbGetPostById(req.params.id);
res.json({ success: true, post: updatedPost });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// Delete a post
app.delete("/api/posts/:id", (req, res) => {
const post = dbGetPostById(req.params.id);
if (!post) return res.status(404).json({ error: "Post nicht gefunden" });
// Cancel any scheduled job
cancelJob(`post-${post.id}`);
dbDeletePost(req.params.id);
res.json({ success: true });
});
// Publish a post immediately
app.post("/api/posts/:id/publish", optionalAuth, async (req, res) => {
if (!rateLimitCustom(req.ip, 10)) return res.status(429).json({ error: "Rate limit" });
// Check plan limits if user is logged in
if (req.user) {
const plan = PLANS[req.user.plan || "free"];
if (plan.postsPerMonth !== -1 && req.user.postsThisMonth >= plan.postsPerMonth) {
return res.status(403).json({ error: `Post-Limit erreicht (${plan.postsPerMonth}/Monat). Upgrade deinen Plan.` });
}
}
const post = dbGetPostById(req.params.id);
if (!post) return res.status(404).json({ error: "Post nicht gefunden" });
if (post.status === "posted") return res.status(400).json({ error: "Bereits gepostet" });
if (post.platforms.length === 0) return res.status(400).json({ error: "Keine Plattformen ausgewaehlt" });
const results = {};
for (const platform of post.platforms) {
try {
// Build payload with media
const payload = { text: post.text };
const imageMedia = post.media.find(m => m.type === "image");
if (imageMedia) payload.imageUrl = `${BACKEND_URL}${imageMedia.url}`;
results[platform] = await postContent(platform, payload);
} catch (err) {
results[platform] = { success: false, error: err.message };
}
}
dbUpdatePost(post.id, {
status: "posted",
postedAt: new Date().toISOString(),
postResults: results,
});
// Increment post counter
if (req.user) incrementPostCount(req.user.id);
// Cancel any scheduled job
cancelJob(`post-${post.id}`);
addLog({ type: "own_post_published", postId: post.id, platforms: post.platforms, results });
res.json({ success: true, results });
});
// Duplicate a post
app.post("/api/posts/:id/duplicate", (req, res) => {
const original = dbGetPostById(req.params.id);
if (!original) return res.status(404).json({ error: "Post nicht gefunden" });
const dupe = {
...original,
id: crypto.randomUUID(),
status: "draft",
scheduledAt: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
postedAt: null,
postResults: null,
};
dbInsertPost(dupe);
res.json({ success: true, post: dupe });
});
// Get post stats
app.get("/api/posts/stats/overview", (_req, res) => {
const posts = dbGetAllPosts();
res.json({
total: posts.length,
drafts: posts.filter(p => p.status === "draft").length,
scheduled: posts.filter(p => p.status === "scheduled").length,
posted: posts.filter(p => p.status === "posted").length,
});
});
const MODELS = {
// Anthropic
"claude-sonnet": { provider: "anthropic", model: "claude-sonnet-4-20250514" },
"claude-haiku": { provider: "anthropic", model: "claude-haiku-4-5-20251001" },
"claude-opus": { provider: "anthropic", model: "claude-opus-4-20250115" },
// OpenAI
"gpt-4o": { provider: "openai", model: "gpt-4o" },
"gpt-4o-mini": { provider: "openai", model: "gpt-4o-mini" },
"gpt-4-turbo": { provider: "openai", model: "gpt-4-turbo" },
// Ollama (lokal)
"ollama-llama3": { provider: "ollama", model: "llama3" },
"ollama-mistral": { provider: "ollama", model: "mistral" },
"ollama-gemma2": { provider: "ollama", model: "gemma2" },
};
// List available models + check which providers have keys configured
app.get("/api/models", (req, res) => {
const userKeys = extractUserKeys(req);
const available = Object.entries(MODELS).map(([id, { provider, model }]) => {
let ready = false;
if (provider === "anthropic") ready = !!(getApiKey("anthropic", userKeys));
else if (provider === "openai") ready = !!(getApiKey("openai", userKeys));
else if (provider === "ollama") ready = true;
return { id, provider, model, ready };
});
const budget = getAIBudgetRemaining(req.ip);
res.json({ models: available, freemium: true, byok: isByok(userKeys), ...budget });
});
// Generate content
app.post("/api/generate", aiLimiter, async (req, res) => {
const userKeys = extractUserKeys(req);
const byok = isByok(userKeys);
if (!rateLimitCustom(`ai:${req.ip}`, 10)) return res.status(429).json({ error: "Max 10 AI-Calls/Minute. Bitte warte kurz." });
if (!byok && !checkAIBudget(req.ip)) return res.status(429).json({ error: `Tages-Limit erreicht (${AI_DAILY_LIMIT} AI-Calls/Tag). Eigene API-Keys eingeben für unbegrenzte Nutzung.`, needsKeys: true, ...getAIBudgetRemaining(req.ip) });
const { modelId, prompt } = req.body;
try {
validateString(modelId, "modelId", { required: true, maxLength: 50 });
validateString(prompt, "prompt", { required: true, maxLength: 50000 });
} catch (err) {
return res.status(400).json({ error: err.message });
}
const config = MODELS[modelId];
if (!config) return res.status(400).json({ error: `Unknown model: ${modelId}` });
try {
let text;
if (config.provider === "anthropic") {
const key = getApiKey("anthropic", userKeys);
if (!key) return res.status(400).json({ error: "Kein Anthropic API-Key verfügbar. Bitte eigenen Key eingeben.", needsKeys: true });
const resp = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": key,
"anthropic-version": "2023-06-01",
},
body: JSON.stringify({
model: config.model,
max_tokens: 4000,
messages: [{ role: "user", content: prompt }],
}),
});
if (!resp.ok) {
const err = await resp.text();
return res.status(resp.status).json({ error: `Anthropic API: ${err}` });
}
const data = await resp.json();
text = data.content?.map(b => b.text || "").join("\n") || "";
} else if (config.provider === "openai") {
const key = getApiKey("openai", userKeys);
if (!key) return res.status(400).json({ error: "Kein OpenAI API-Key verfügbar. Bitte eigenen Key eingeben.", needsKeys: true });
const resp = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${key}`,
},
body: JSON.stringify({
model: config.model,
max_tokens: 4000,
messages: [{ role: "user", content: prompt }],
}),
});
if (!resp.ok) {
const err = await resp.text();
return res.status(resp.status).json({ error: `OpenAI API: ${err}` });
}
const data = await resp.json();
text = data.choices?.[0]?.message?.content || "";
} else if (config.provider === "ollama") {
const base = process.env.OLLAMA_BASE_URL || "http://localhost:11434";
const resp = await fetch(`${base}/api/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: config.model,
messages: [{ role: "user", content: prompt }],
stream: false,
}),
});
if (!resp.ok) {
const err = await resp.text();
return res.status(resp.status).json({ error: `Ollama: ${err}` });
}
const data = await resp.json();
text = data.message?.content || "";
}
const remaining = byok ? null : getAIBudgetRemaining(req.ip);
res.json({ text, ...(remaining && { remaining: remaining.remaining, limit: remaining.limit }) });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// --- Engagement Engine Endpoints ---
import {
DEFAULT_PERSONALITY,
ENGAGEMENT_RULES_TEMPLATE,
buildEngagementPrompt,
humanize,
naturalDelay,
pickTemplate,
generatePostSchedule,
} from "./engagement-engine.js";
const CONFIG_PATH = "./engagement-config.json";
function loadEngagementConfig() {
if (fsExists(CONFIG_PATH)) {
return JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
}
return {
personality: { ...DEFAULT_PERSONALITY },
rules: [...ENGAGEMENT_RULES_TEMPLATE],
platforms: {
youtube: { enabled: false, connected: false },
x: { enabled: false, connected: false },
instagram: { enabled: false, connected: false },
tiktok: { enabled: false, connected: false },
linkedin: { enabled: false, connected: false },
xing: { enabled: false, connected: false },
},
scheduledPosts: [],
active: false,
};
}
function saveEngagementConfig(config) {
writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
}
// Get engagement config
app.get("/api/engagement/config", (_req, res) => {
res.json(loadEngagementConfig());
});
// Update engagement config
app.post("/api/engagement/config", (req, res) => {
const current = loadEngagementConfig();
const updated = { ...current, ...req.body };
saveEngagementConfig(updated);
res.json(updated);
});
// Update personality
app.post("/api/engagement/personality", (req, res) => {
const config = loadEngagementConfig();
config.personality = { ...config.personality, ...req.body };
saveEngagementConfig(config);
res.json(config.personality);
});
// Update engagement rules
app.post("/api/engagement/rules", (req, res) => {
const config = loadEngagementConfig();
config.rules = req.body.rules || config.rules;
saveEngagementConfig(config);
res.json(config.rules);
});
// Generate a natural engagement reply using AI
app.post("/api/engagement/generate-reply", aiLimiter, async (req, res) => {
const userKeys = extractUserKeys(req);
const byok = isByok(userKeys);
if (!rateLimitCustom(`ai:${req.ip}`, 10)) return res.status(429).json({ error: "Max 10 Reply-Calls/Minute." });
if (!byok && !checkAIBudget(req.ip)) return res.status(429).json({ error: `Tages-Limit erreicht (${AI_DAILY_LIMIT}/Tag). Eigene API-Keys eingeben für unbegrenzte Nutzung.`, needsKeys: true, ...getAIBudgetRemaining(req.ip) });
const { platform, postContent: postContentText, commentToReply, modelId } = req.body;
const config = loadEngagementConfig();
const prompt = buildEngagementPrompt(
{ platform, postContent: postContentText, commentToReply },
config.personality
);
const mid = modelId || "claude-sonnet";
const modelConfig = MODELS[mid];
if (!modelConfig) return res.status(400).json({ error: `Unknown model: ${mid}` });
try {
let text = "";
if (modelConfig.provider === "anthropic") {
const key = getApiKey("anthropic", userKeys);
if (!key) return res.status(400).json({ error: "Kein Anthropic API-Key verfügbar.", needsKeys: true });
const resp = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: { "Content-Type": "application/json", "x-api-key": key, "anthropic-version": "2023-06-01" },
body: JSON.stringify({ model: modelConfig.model, max_tokens: 200, messages: [{ role: "user", content: prompt }] }),
});
const data = await resp.json();
text = data.content?.map(b => b.text || "").join("") || "";
} else if (modelConfig.provider === "openai") {
const key = getApiKey("openai", userKeys);
if (!key) return res.status(400).json({ error: "Kein OpenAI API-Key verfügbar.", needsKeys: true });
const resp = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${key}` },
body: JSON.stringify({ model: modelConfig.model, max_tokens: 200, messages: [{ role: "user", content: prompt }] }),
});
const data = await resp.json();
text = data.choices?.[0]?.message?.content || "";
} else if (modelConfig.provider === "ollama") {
const base = process.env.OLLAMA_BASE_URL || "http://localhost:11434";
const resp = await fetch(`${base}/api/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: modelConfig.model, messages: [{ role: "user", content: prompt }], stream: false }),
});
const data = await resp.json();
text = data.message?.content || "";
}
// Apply human-like imperfections
text = humanize(text.trim(), config.personality.typoRate);
const delay = naturalDelay(config.personality.responseDelay.min, config.personality.responseDelay.max);
res.json({ reply: text, suggestedDelay: delay });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Schedule posts with natural timing
app.post("/api/engagement/schedule", (req, res) => {
const config = loadEngagementConfig();
const { posts } = req.body;
const schedule = generatePostSchedule(posts, config.personality);
config.scheduledPosts = [...config.scheduledPosts, ...schedule];
saveEngagementConfig(config);
res.json({ scheduled: schedule });
});
// Toggle engagement engine on/off
app.post("/api/engagement/toggle", (req, res) => {
const config = loadEngagementConfig();
config.active = req.body.active ?? !config.active;
saveEngagementConfig(config);
res.json({ active: config.active });
});
// --- Platform OAuth & Posting ---
const SUPPORTED_PLATFORMS = ["youtube", "x", "instagram", "tiktok", "linkedin"];
const APP_URL = process.env.APP_URL || "http://localhost:5173";
// Get connection status for all platforms
app.get("/api/platforms", (_req, res) => {
const tokens = loadTokens();
const status = {};
for (const p of SUPPORTED_PLATFORMS) {
const t = tokens[p];
status[p] = {
connected: !!t?.accessToken,
name: t?.channelName || t?.username || t?.igUsername || t?.name || t?.openId || null,
hasCredentials: !!(
(p === "youtube" && process.env.YOUTUBE_CLIENT_ID) ||
(p === "x" && process.env.X_CLIENT_ID) ||
(p === "instagram" && process.env.META_APP_ID) ||
(p === "tiktok" && process.env.TIKTOK_CLIENT_KEY) ||
(p === "linkedin" && process.env.LINKEDIN_CLIENT_ID)
),
};
}
res.json(status);
});
// Start OAuth flow -- returns the authorization URL
app.get("/auth/:platform/connect", (req, res) => {
const { platform } = req.params;
if (!SUPPORTED_PLATFORMS.includes(platform)) return res.status(400).json({ error: "Unknown platform" });
const url = getAuthUrl(platform);
if (!url) return res.status(400).json({ error: `Missing credentials for ${platform} in .env` });
res.json({ authUrl: url });
});
// OAuth callbacks
for (const platform of SUPPORTED_PLATFORMS) {
app.get(`/auth/${platform}/callback`, async (req, res) => {
const { code, error } = req.query;
if (error) return res.redirect(`${APP_URL}?platform=${platform}&error=${encodeURIComponent(error)}`);
if (!code) return res.redirect(`${APP_URL}?platform=${platform}&error=no_code`);
try {
const result = await exchangeCode(platform, code);
if (result.success) {
res.redirect(`${APP_URL}?platform=${platform}&connected=true`);
} else {
res.redirect(`${APP_URL}?platform=${platform}&error=${encodeURIComponent(result.error || "unknown")}`);
}
} catch (err) {
res.redirect(`${APP_URL}?platform=${platform}&error=${encodeURIComponent(err.message)}`);
}
});
}
// Disconnect platform
app.post("/auth/:platform/disconnect", (req, res) => {
removeToken(req.params.platform);
res.json({ disconnected: true });
});
// Post content to a platform
app.post("/api/platforms/:platform/post", async (req, res) => {
const { platform } = req.params;
const { text, imageUrl } = req.body;
try {
const result = await postContent(platform, { text, imageUrl });
res.json(result);
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// Post to multiple platforms at once
app.post("/api/platforms/post-all", async (req, res) => {
const { text, imageUrl, platforms: targetPlatforms } = req.body;
const results = {};
for (const p of (targetPlatforms || SUPPORTED_PLATFORMS)) {