-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
541 lines (468 loc) · 19.3 KB
/
server.js
File metadata and controls
541 lines (468 loc) · 19.3 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
import axios from 'axios';
import { exec } from 'child_process';
import cors from 'cors';
import 'dotenv/config';
import express from 'express';
import fs from 'fs-extra';
import matter from 'gray-matter';
import { marked } from 'marked';
import multer from 'multer';
import path from 'path';
import TurndownService from 'turndown';
import { fileURLToPath } from 'url';
import { promisify } from 'util';
import bcrypt from 'bcryptjs';
import session from 'express-session';
const execAsync = promisify(exec);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const port = process.env.SERVER_PORT;
app.use(cors());
app.use(express.json({ limit: '50mb' }));
// Configuration from Env
const CONTENT_DIR_REL = process.env.CONTENT_DIR;
const STATIC_DIR_REL = process.env.STATIC_DIR;
const DRAFTS_DIR_REL = process.env.DRAFTS_DIR;
const POSTS_DIR = path.resolve(__dirname, CONTENT_DIR_REL);
const STATIC_DIR = path.resolve(__dirname, STATIC_DIR_REL);
const DRAFTS_DIR = path.resolve(__dirname, DRAFTS_DIR_REL);
// Auth Configuration
const AUTH_ENABLED = process.env.AUTH_ENABLED === 'true';
const AUTH_USERNAME = process.env.AUTH_USERNAME;
// Docker Compose may use $$ to escape $, so we unescape it for the app
const AUTH_PASSWORD_HASH = process.env.AUTH_PASSWORD_HASH?.replace(/\$\$/g, '$');
const SESSION_SECRET = process.env.SESSION_SECRET?.replace(/\$\$/g, '$') || 'inscript-secret';
// Auth Middleware
const authGuard = (req, res, next) => {
if (!AUTH_ENABLED) return next();
if (req.session.user) return next();
// Allow public access to auth routes and /api/me
if (req.path.startsWith('/api/me') || req.path === '/auth/login' || req.path === '/auth/logout') return next();
res.status(401).json({ error: 'Unauthorized' });
};
if (AUTH_ENABLED) {
app.use(session({
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // Set to true if using HTTPS
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));
}
// Auth Routes
if (AUTH_ENABLED) {
app.post('/auth/login', async (req, res) => {
const { username, password } = req.body;
if (!AUTH_USERNAME || !AUTH_PASSWORD_HASH) {
return res.status(500).json({ error: 'Server authentication not configured correctly' });
}
if (username === AUTH_USERNAME) {
const match = await bcrypt.compare(password, AUTH_PASSWORD_HASH);
if (match) {
req.session.user = { displayName: AUTH_USERNAME };
return res.json({ success: true, user: req.session.user });
}
}
res.status(401).json({ error: 'Invalid username or password' });
});
app.get('/api/me', (req, res) => {
res.json({
user: req.session.user || null,
authEnabled: true,
authType: 'manual'
});
});
app.get('/auth/logout', (req, res) => {
req.session.destroy();
res.json({ success: true });
});
} else {
app.get('/api/me', (req, res) => {
res.json({ user: { displayName: 'Guest' }, authEnabled: false });
});
}
// Apply authGuard to all /api routes
app.use('/api', authGuard);
console.log('Inscript Config:');
console.log('Posts Dir:', POSTS_DIR);
console.log('Static Dir:', STATIC_DIR);
console.log('Drafts Dir:', DRAFTS_DIR);
// Serve custom favicon
app.get('/favicon.png', (req, res) => {
const FAVICON_FILE = process.env.FAVICON;
if (FAVICON_FILE && !FAVICON_FILE.includes('favicon_default.png')) {
const customFaviconPath = path.resolve(STATIC_DIR, FAVICON_FILE);
if (fs.existsSync(customFaviconPath)) {
return res.sendFile(customFaviconPath);
}
}
// Fallback to default
const defaultFavicon = path.join(__dirname, 'assets', 'favicon_default.png');
if (fs.existsSync(defaultFavicon)) {
res.sendFile(defaultFavicon);
} else {
res.status(404).send('Favicon not found');
}
});
// Serve static files from the configured static directory
app.use(express.static(STATIC_DIR));
// Ensure directories exist
fs.ensureDirSync(POSTS_DIR);
fs.ensureDirSync(DRAFTS_DIR);
// Configure Turndown
const turndownService = new TurndownService({
headingStyle: 'atx',
codeBlockStyle: 'fenced'
});
// Helper to convert Hugo shortcodes to HTML
const processShortcodes = (markdown) => {
// Youtube: {{< youtube ID >}}
return markdown.replace(/{{<\s*youtube\s+([a-zA-Z0-9_-]+)\s*>}}/g, (match, id) => {
return `<div data-youtube-video="${id}" class="youtube-embed relative w-full aspect-video rounded-lg overflow-hidden my-4"><iframe src="https://www.youtube.com/embed/${id}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen class="absolute top-0 left-0 w-full h-full"></iframe></div>`;
});
};
// Turndown Rule for Youtube
turndownService.addRule('youtube', {
filter: (node) => {
return node.nodeName === 'DIV' && node.getAttribute('data-youtube-video');
},
replacement: (content, node) => {
const id = node.getAttribute('data-youtube-video');
return `{{< youtube ${id} >}}`;
}
});
// Configure Marked
marked.setOptions({
gfm: true,
breaks: true,
});
// Configure Multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, STATIC_DIR);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, uniqueSuffix + path.extname(file.originalname));
}
});
const upload = multer({ storage });
// List all posts
app.get('/api/youtube/search', async (req, res) => {
const { q } = req.query;
if (!q) return res.json({ items: [] });
const SOURCES = [
{ url: 'https://invidious.ducks.party', type: 'invidious' }, // Verified working Feb 2026
{ url: 'https://iv.ggtyler.dev', type: 'invidious' },
{ url: 'https://invidious.projectsegfau.lt', type: 'invidious' },
{ url: 'https://pipedapi.tokhmi.xyz', type: 'piped' },
{ url: 'https://pipedapi.lunar.icu', type: 'piped' },
{ url: 'https://api.piped.yt', type: 'piped' }
];
const axiosConfig = {
timeout: 5000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
};
for (const source of SOURCES) {
try {
if (source.type === 'piped') {
const response = await axios.get(`${source.url}/search?q=${encodeURIComponent(q)}&filter=videos`, axiosConfig);
if (response.data && response.data.items) {
return res.json(response.data);
}
} else if (source.type === 'invidious') {
const response = await axios.get(`${source.url}/api/v1/search?q=${encodeURIComponent(q)}&type=video`, axiosConfig);
if (Array.isArray(response.data)) {
const items = response.data.map(v => ({
url: `/watch?v=${v.videoId}`,
title: v.title,
thumbnail: v.videoThumbnails?.find(t => t.quality === 'medium')?.url || v.videoThumbnails?.[0]?.url,
uploaderName: v.author,
views: v.viewCount,
duration: v.lengthSeconds
}));
return res.json({ items });
}
}
} catch (err) {
console.warn(`YouTube Search failed for ${source.url}: ${err.code || err.response?.status || err.message}`);
continue;
}
}
res.status(502).json({ error: 'All YouTube search sources failed' });
});
app.get('/api/posts', async (req, res) => {
try {
const files = await fs.readdir(POSTS_DIR);
const draftFiles = await fs.readdir(DRAFTS_DIR).catch(() => []);
const posts = await Promise.all(
files.filter(f => f.endsWith('.md')).map(async (filename) => {
const filePath = path.join(POSTS_DIR, filename);
const content = await fs.readFile(filePath, 'utf8');
const stats = await fs.stat(filePath);
const { data } = matter(content);
const hasDraft = draftFiles.includes(`${filename}.json`);
// Use frontmatter created/modified or fallback to file stats
const created = data.created
? new Date(data.created).toISOString()
: (stats.birthtime || stats.ctime).toISOString();
const modified = data.modified
? new Date(data.modified).toISOString()
: stats.mtime.toISOString();
return {
filename,
title: data.title || filename,
created,
modified,
hasDraft,
isUnpublished: false,
tags: data.tags || [],
categories: data.categories || [],
...data // Spread other frontmatter fields like 'type'
};
})
);
// Handle Orphan Drafts (Unpublished Posts)
const publishedFilenames = new Set(files.filter(f => f.endsWith('.md')));
const orphanDrafts = draftFiles.filter(f => f.endsWith('.md.json') && !publishedFilenames.has(f.replace('.json', '')));
const unpublishedPosts = await Promise.all(
orphanDrafts.map(async (draftFilename) => {
const filePath = path.join(DRAFTS_DIR, draftFilename);
const draft = await fs.readJson(filePath);
const filename = draftFilename.replace('.json', '');
// Get latest state from history
const latest = (draft.history && draft.history[draft.currentIndex]) ||
(draft.history && draft.history.length > 0 ? draft.history[draft.history.length - 1] : null) ||
{ title: filename.replace('.md', ''), timestamp: new Date().toISOString() };
return {
filename,
title: latest.title || filename,
created: latest.timestamp, // Draft creation/mod time
modified: latest.timestamp,
hasDraft: true,
isUnpublished: true,
tags: latest.tags || [],
categories: latest.categories || [],
type: draft.type
};
})
);
res.json([...posts, ...unpublishedPosts]);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Get single post (with merged draft if exists)
app.get('/api/posts/:filename', async (req, res) => {
try {
const filePath = path.join(POSTS_DIR, req.params.filename);
const draftPath = path.join(DRAFTS_DIR, `${req.params.filename}.json`);
let frontmatter = {};
let html = '';
let title = req.params.filename.replace('.md', '');
let savedHtml = '';
let savedTitle = '';
let isUnpublished = false;
// Check if original file exists
const fileExists = await fs.pathExists(filePath);
if (fileExists) {
const content = await fs.readFile(filePath, 'utf8');
const parsed = matter(content);
frontmatter = parsed.data;
frontmatter = parsed.data;
const markdown = processShortcodes(parsed.content);
html = marked.parse(markdown);
title = frontmatter.title || title;
savedHtml = html;
savedTitle = title;
} else {
// Check if it's an unpublished draft
const draftExists = await fs.pathExists(draftPath);
if (!draftExists) {
return res.status(404).json({ error: 'Post not found' });
}
isUnpublished = true;
}
let history = [];
let currentIndex = 0;
const hasDraft = await fs.pathExists(draftPath);
if (hasDraft) {
const draft = await fs.readJson(draftPath);
const activeItem = draft.history && draft.history[draft.currentIndex];
if (activeItem) {
// Drafts store HTML directly, but if we ever re-parse raw MD, we might need this.
// Currently draft history is HTML. If the draft was loaded from MD initially, it already went through processShortcodes.
html = activeItem.html;
title = activeItem.title;
}
history = draft.history || [];
currentIndex = draft.currentIndex || 0;
// For unpublished drafts, populate frontmatter from latest draft state
if (isUnpublished && activeItem) {
frontmatter = {
title: activeItem.title,
tags: activeItem.tags || [],
categories: activeItem.categories || [],
created: activeItem.timestamp,
modified: activeItem.timestamp
};
savedTitle = activeItem.title;
// savedHtml remains empty for unpublished drafts as there is no "published" version
}
}
res.json({ filename: req.params.filename, frontmatter, html, title, savedHtml, savedTitle, hasDraft, history, currentIndex, isUnpublished });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Save post (and clear draft)
app.post('/api/posts', async (req, res) => {
try {
const { filename, frontmatter, html } = req.body;
const markdown = turndownService.turndown(html);
// Enforce modified time. Preserve existing created time or set it if missing.
const now = new Date().toISOString();
frontmatter.modified = now;
if (!frontmatter.created) {
frontmatter.created = now;
}
const fileContent = matter.stringify(markdown, frontmatter);
await fs.writeFile(path.join(POSTS_DIR, filename), fileContent);
// Clear draft on successful permanent save
const draftPath = path.join(DRAFTS_DIR, `${filename}.json`);
await fs.remove(draftPath).catch(() => { });
res.json({ success: true, frontmatter });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Draft Management
app.post('/api/drafts/:filename', async (req, res) => {
try {
const { title, history, currentIndex } = req.body;
const draftPath = path.join(DRAFTS_DIR, `${req.params.filename}.json`);
// Server is now a dumb store for the client-managed history stack
await fs.writeJson(draftPath, {
history,
currentIndex
}, { spaces: 4 });
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.delete('/api/drafts/:filename', async (req, res) => {
try {
const draftPath = path.join(DRAFTS_DIR, `${req.params.filename}.json`);
await fs.remove(draftPath);
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Publish static site
app.post('/api/publish', async (req, res) => {
try {
console.log('🚀 Publishing static site...');
// Execute the publish script defined in package.json
// Increase maxBuffer for large Vite build outputs (10MB)
const { stdout, stderr } = await execAsync('npm run publish', {
cwd: __dirname,
maxBuffer: 10 * 1024 * 1024
});
console.log('Publish Output:', stdout);
if (stderr) console.error('Publish Error Output:', stderr);
res.json({ success: true, output: stdout });
} catch (err) {
console.error('Publish Failed:', err);
// Include stderr in the error response if available for better debugging
const errorMessage = err.stderr ? `${err.message}\n\nStderr: ${err.stderr}` : err.message;
res.status(500).json({ error: errorMessage });
}
});
// Git Commit
app.post('/api/git/commit', async (req, res) => {
try {
const { message, filename } = req.body;
console.log(`📝 Committing changes: ${message}`);
// Ensure we are in the project root (one level up from inscript/ if server.js is in inscript/)
const projectRoot = path.join(__dirname, '..');
// Add all changes (or could be specific to filename if provided)
await execAsync('git add .', { cwd: projectRoot });
const { stdout } = await execAsync(`git commit -m "${message || 'Update blog content'}"`, { cwd: projectRoot });
res.json({ success: true, output: stdout });
} catch (err) {
// If nothing to commit, git commit returns non-zero. Check for that.
if (err.stdout && err.stdout.includes('nothing to commit')) {
return res.json({ success: true, output: 'Nothing to commit, working tree clean' });
}
res.status(500).json({ error: err.message });
}
});
// Git Push
app.post('/api/git/push', async (req, res) => {
try {
console.log('⬆️ Pushing to remote...');
const projectRoot = path.join(__dirname, '..');
const { stdout } = await execAsync('git push', { cwd: projectRoot });
res.json({ success: true, output: stdout });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.delete('/api/posts/:filename', async (req, res) => {
try {
const { filename } = req.params;
const filePath = path.join(POSTS_DIR, filename);
const draftPath = path.join(DRAFTS_DIR, `${filename}.json`);
if (await fs.pathExists(filePath)) await fs.remove(filePath);
if (await fs.pathExists(draftPath)) await fs.remove(draftPath);
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Upload image
app.post('/api/upload', upload.single('image'), (req, res) => {
try {
if (!req.file) throw new Error('No file uploaded');
res.json({ url: req.file.filename });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Helper for recursive files
async function getFiles(dir) {
const subdirs = await fs.readdir(dir);
const files = await Promise.all(subdirs.map(async (subdir) => {
const res = path.resolve(dir, subdir);
return (await fs.stat(res)).isDirectory() ? await getFiles(res) : res;
}));
return Array.prototype.concat(...files);
}
app.get('/api/images', async (req, res) => {
try {
const allFiles = await getFiles(STATIC_DIR);
const images = allFiles
.filter(f => /\.(png|jpg|jpeg|gif|svg|webp)$/i.test(f))
.map(fullPath => {
const relativePath = path.relative(STATIC_DIR, fullPath);
return {
url: `/${relativePath}`,
name: relativePath
};
});
res.json(images);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(port, '0.0.0.0', () => {
console.log(`Inscript Server running at http://0.0.0.0:${port}`);
});