BlueGit

timfa filemanager

Files

filemanager / server / routes / share.js

share.js

Fix My Folder access paths
timfa Tim Falken · pushed by timfa · 6 months ago
7c87f490 History
share.js 15.2 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const crypto = require('crypto');
7const archiver = require('archiver');
8const router = express.Router();
9
10const { getDb } = require('../db');
11const { requireAuth } = require('../auth');
12const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config');
13const { createVideoStreamSession, sendVideoStreamAsset } = require('../video-stream');
14
15const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
16const ZIP_CACHE_DIR = path.join(__dirname, '../../zip-cache');
17const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
18
19// ---------------------------------------------------------------------------
20// Helpers
21// ---------------------------------------------------------------------------
22
23function effectivePaths ()
24{
25 return getEffectivePaths(loadConfig().paths || []);
26}
27
28/** Returns the configured root that contains absPath, or null. */
29function resolveRoot (absPath)
30{
31 return getAllowedRoot(absPath, effectivePaths());
32}
33
34function getUserFolderPath (config, username)
35{
36 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
37 if (!base) return null;
38 return path.join(base, String(username));
39}
40
41function resolveRootForUser (absPath, roots, user, config)
42{
43 const matched = getAllowedRoot(absPath, roots);
44 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
45
46 if (!user || !user.username) return null;
47 const userFolder = getUserFolderPath(config, user.username);
48 if (!userFolder) return null;
49
50 const resolved = path.resolve(absPath);
51 const resolvedFolder = path.resolve(userFolder);
52 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
53 {
54 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
55 }
56
57 return null;
58}
59
60function canReadInfo (user, info)
61{
62 if (!info) return false;
63 if (info.isUserFolder) return true;
64 if (user.isAdmin) return true;
65 return !!(user.permissions[info.label] && user.permissions[info.label].read);
66}
67
68/** Generate a cryptographically random token. */
69function generateToken ()
70{
71 return crypto.randomBytes(32).toString('hex');
72}
73
74/** Ensure the zip cache directory exists. */
75function ensureZipCacheDir ()
76{
77 if (!fs.existsSync(ZIP_CACHE_DIR))
78 {
79 fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true });
80 }
81}
82
83/**
84 * Delete zip files in ZIP_CACHE_DIR that are older than ZIP_MAX_AGE_MS.
85 * Also delete zip files whose corresponding share token has expired.
86 */
87function pruneZipCache ()
88{
89 ensureZipCacheDir();
90 const now = Date.now();
91 let entries;
92 try
93 {
94 entries = fs.readdirSync(ZIP_CACHE_DIR);
95 } catch
96 {
97 return;
98 }
99
100 for (const name of entries)
101 {
102 if (!name.endsWith('.zip')) continue;
103 const fullPath = path.join(ZIP_CACHE_DIR, name);
104 try
105 {
106 const stat = fs.statSync(fullPath);
107 const age = now - stat.mtimeMs;
108 if (age > ZIP_MAX_AGE_MS)
109 {
110 fs.unlinkSync(fullPath);
111 }
112 } catch
113 {
114 // Ignore files that disappeared.
115 }
116 }
117}
118
119/**
120 * Create (or return cached) zip for the given directory.
121 * cacheKey is used as the filename stem.
122 * Returns the full path to the zip file.
123 */
124function buildZip (dirPath, cacheKey)
125{
126 return new Promise((resolve, reject) =>
127 {
128 ensureZipCacheDir();
129 pruneZipCache();
130
131 const zipPath = path.join(ZIP_CACHE_DIR, `${cacheKey}.zip`);
132
133 // Serve cached version if it exists and is not too old.
134 if (fs.existsSync(zipPath))
135 {
136 try
137 {
138 const stat = fs.statSync(zipPath);
139 if (Date.now() - stat.mtimeMs < ZIP_MAX_AGE_MS)
140 {
141 return resolve(zipPath);
142 }
143 fs.unlinkSync(zipPath);
144 } catch { /* fall through to rebuild */ }
145 }
146
147 const tmpPath = zipPath + '.tmp';
148 const output = fs.createWriteStream(tmpPath);
149 const archive = archiver('zip', { zlib: { level: 6 } });
150
151 output.on('close', () =>
152 {
153 try
154 {
155 fs.renameSync(tmpPath, zipPath);
156 resolve(zipPath);
157 } catch (err)
158 {
159 reject(err);
160 }
161 });
162
163 archive.on('error', (err) =>
164 {
165 try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
166 reject(err);
167 });
168
169 archive.pipe(output);
170 archive.directory(dirPath, path.basename(dirPath));
171 archive.finalize();
172 });
173}
174
175// ---------------------------------------------------------------------------
176// POST /api/share/create
177// Body: { filePath: <absolute-path> }
178// Authenticated. Creates a 24-hour share token for a file or directory.
179// ---------------------------------------------------------------------------
180router.post('/create', requireAuth, (req, res) =>
181{
182 const filePath = String((req.body && req.body.filePath) || '').trim();
183 if (!filePath)
184 {
185 return res.status(400).json({ error: 'filePath is required.' });
186 }
187
188 const config = loadConfig();
189 const roots = effectivePaths();
190 const info = resolveRootForUser(filePath, roots, req.user, config);
191 if (!info || !canReadInfo(req.user, info))
192 {
193 return res.status(403).json({ error: 'Access denied.' });
194 }
195
196 let stat;
197 try
198 {
199 stat = fs.statSync(filePath);
200 } catch
201 {
202 return res.status(404).json({ error: 'File or folder not found.' });
203 }
204
205 const isDir = stat.isDirectory() ? 1 : 0;
206 const now = Date.now();
207 const expiresAt = now + SHARE_TTL_MS;
208 const token = generateToken();
209 const user = req.user;
210
211 const db = getDb();
212 db.prepare(`
213 INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at)
214 VALUES (?, ?, ?, ?, ?, ?)
215 `).run([token, filePath, isDir, user.username, now, expiresAt]);
216
217 res.json({ token, expiresAt });
218});
219
220// ---------------------------------------------------------------------------
221// GET /api/share/info/:token
222// Public (no auth). Returns metadata about the shared item.
223// ---------------------------------------------------------------------------
224router.get('/info/:token', (req, res) =>
225{
226 const token = String(req.params.token || '').trim();
227 if (!token) return res.status(400).json({ error: 'Token is required.' });
228
229 const db = getDb();
230 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
231
232 if (!row) return res.status(404).json({ error: 'Share link not found.' });
233 if (Date.now() > row.expires_at)
234 {
235 return res.status(410).json({ error: 'Share link has expired.' });
236 }
237
238 const name = path.basename(row.file_path);
239 res.json({
240 name,
241 isDir: !!row.is_dir,
242 expiresAt: row.expires_at,
243 });
244});
245
246// ---------------------------------------------------------------------------
247// GET /api/share/preview/:token
248// Public (no auth). Streams a file for inline preview (non-directory only).
249// ---------------------------------------------------------------------------
250router.get('/preview/:token', (req, res) =>
251{
252 const token = String(req.params.token || '').trim();
253 if (!token) return res.status(400).json({ error: 'Token is required.' });
254
255 const db = getDb();
256 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
257
258 if (!row) return res.status(404).json({ error: 'Share link not found.' });
259 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
260 if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' });
261
262 if (!fs.existsSync(row.file_path))
263 {
264 return res.status(404).json({ error: 'File not found.' });
265 }
266
267 // Limit preview size to 50 MB to prevent accidental large file streaming.
268 const MAX_PREVIEW_BYTES = 50 * 1024 * 1024;
269 let stat;
270 try { stat = fs.statSync(row.file_path); } catch { return res.status(404).json({ error: 'File not found.' }); }
271
272 if (stat.size > MAX_PREVIEW_BYTES)
273 {
274 return res.status(413).json({ error: 'File too large for inline preview.' });
275 }
276
277 res.set('Cache-Control', 'private, no-store');
278 res.sendFile(row.file_path);
279});
280
281// ---------------------------------------------------------------------------
282// GET /api/share/video-stream/:token
283// Public (no auth). Creates a short-lived ffmpeg-backed HLS session.
284// ---------------------------------------------------------------------------
285router.get('/video-stream/:token', async (req, res, next) =>
286{
287 try
288 {
289 const token = String(req.params.token || '').trim();
290 if (!token) return res.status(400).json({ error: 'Token is required.' });
291
292 const db = getDb();
293 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
294
295 if (!row) return res.status(404).json({ error: 'Share link not found.' });
296 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
297 if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' });
298
299 if (!fs.existsSync(row.file_path) || fs.statSync(row.file_path).isDirectory())
300 {
301 return res.status(404).json({ error: 'File not found.' });
302 }
303
304 const session = await createVideoStreamSession(row.file_path);
305 res.json({
306 sessionId: session.sessionId,
307 playlistUrl: `/api/share/video-stream/session/${session.sessionId}/master.m3u8`,
308 durationSeconds: session.durationSeconds || null,
309 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
310 subtitleTracks: session.subtitleTracks.map((track) => ({
311 label: track.label,
312 language: track.language,
313 default: !!track.isDefault,
314 src: `/api/share/video-stream/session/${session.sessionId}/${track.fileName}`,
315 })),
316 });
317 } catch (err)
318 {
319 next(err);
320 }
321});
322
323// ---------------------------------------------------------------------------
324// GET /api/share/video-stream/session/:sessionId/:assetPath(*)
325// Public. Serves HLS assets from an already-created share video session.
326// ---------------------------------------------------------------------------
327router.get('/video-stream/session/:sessionId/:assetPath(*)', async (req, res, next) =>
328{
329 try
330 {
331 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
332 } catch (err)
333 {
334 next(err);
335 }
336});
337
338// ---------------------------------------------------------------------------
339// GET /api/share/download/:token
340// Public (no auth). Streams the file or a zip of the directory.
341// ---------------------------------------------------------------------------
342router.get('/download/:token', async (req, res) =>
343{
344 const token = String(req.params.token || '').trim();
345 if (!token) return res.status(400).json({ error: 'Token is required.' });
346
347 const db = getDb();
348 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
349
350 if (!row) return res.status(404).json({ error: 'Share link not found.' });
351 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
352
353 if (row.is_dir)
354 {
355 if (!fs.existsSync(row.file_path) || !fs.statSync(row.file_path).isDirectory())
356 {
357 return res.status(404).json({ error: 'Directory not found.' });
358 }
359
360 try
361 {
362 const zipPath = await buildZip(row.file_path, token);
363 const zipName = `${path.basename(row.file_path)}.zip`;
364 res.download(zipPath, zipName);
365 } catch (err)
366 {
367 res.status(500).json({ error: 'Failed to create zip archive.' });
368 }
369 } else
370 {
371 if (!fs.existsSync(row.file_path))
372 {
373 return res.status(404).json({ error: 'File not found.' });
374 }
375
376 res.download(row.file_path, path.basename(row.file_path));
377 }
378});
379
380// ---------------------------------------------------------------------------
381// Open Graph helpers
382// ---------------------------------------------------------------------------
383
384const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html');
385const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp']);
386
387function ogEsc (s)
388{
389 return String(s || '')
390 .replace(/&/g, '&amp;')
391 .replace(/</g, '&lt;')
392 .replace(/>/g, '&gt;')
393 .replace(/"/g, '&quot;');
394}
395
396function fileExtLower (name)
397{
398 const i = String(name || '').lastIndexOf('.');
399 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
400}
401
402function formatOgValidity (expiresAt)
403{
404 const ms = expiresAt - Date.now();
405 if (ms <= 0) return null;
406 const h = Math.floor(ms / 3600000);
407 const m = Math.floor((ms % 3600000) / 60000);
408 if (h > 0) return `${h} hour${h !== 1 ? 's' : ''} ${m} minute${m !== 1 ? 's' : ''}`;
409 return `${m} minute${m !== 1 ? 's' : ''}`;
410}
411
412/**
413 * Reads share.html, injects Open Graph meta tags for the given token, and
414 * returns the resulting HTML string. Works for all visitors — crawlers get
415 * the OG data they need; browsers get the same interactive page but with a
416 * dynamic title and preview metadata already in the <head>.
417 */
418function buildShareOpenGraphPage (token, req)
419{
420 const db = getDb();
421 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
422
423 const baseUrl = `${req.protocol}://${req.get('host')}`;
424 const shareUrl = `${baseUrl}/share/${encodeURIComponent(token)}`;
425
426 let pageTitle, ogTitle, ogDesc, ogImageUrl = null, twitterCard;
427
428 if (!row)
429 {
430 pageTitle = 'Link Not Found';
431 ogTitle = 'Link Not Found';
432 ogDesc = 'This shared file link does not exist.';
433 twitterCard = 'summary';
434 }
435 else
436 {
437 const name = path.basename(row.file_path);
438 const expired = Date.now() > row.expires_at;
439
440 if (expired)
441 {
442 pageTitle = `Link Expired \u2014 ${name}`;
443 ogTitle = 'Link Expired';
444 ogDesc = `This shared link for \u201C${name}\u201D has expired.`;
445 twitterCard = 'summary';
446 }
447 else
448 {
449 pageTitle = name;
450 ogTitle = name;
451
452 const validity = formatOgValidity(row.expires_at);
453 const typeLabel = row.is_dir ? 'folder' : 'file';
454 ogDesc = validity
455 ? `Shared ${typeLabel} \u00B7 Valid for ${validity}`
456 : `Shared ${typeLabel}`;
457
458 if (!row.is_dir && OG_IMAGE_EXTS.has(fileExtLower(name)))
459 {
460 ogImageUrl = `${baseUrl}/api/share/preview/${encodeURIComponent(token)}`;
461 twitterCard = 'summary_large_image';
462 }
463 else
464 {
465 twitterCard = 'summary';
466 }
467 }
468 }
469
470 const metaLines = [
471 `<meta property="og:title" content="${ogEsc(ogTitle)}" />`,
472 `<meta property="og:description" content="${ogEsc(ogDesc)}" />`,
473 `<meta property="og:url" content="${ogEsc(shareUrl)}" />`,
474 `<meta property="og:type" content="website" />`,
475 `<meta name="twitter:card" content="${ogEsc(twitterCard)}" />`,
476 `<meta name="twitter:title" content="${ogEsc(ogTitle)}" />`,
477 `<meta name="twitter:description" content="${ogEsc(ogDesc)}" />`,
478 ];
479
480 if (ogImageUrl)
481 {
482 metaLines.push(`<meta property="og:image" content="${ogEsc(ogImageUrl)}" />`);
483 metaLines.push(`<meta name="twitter:image" content="${ogEsc(ogImageUrl)}" />`);
484 }
485
486 const ogBlock = metaLines.join('\n ');
487
488 let html;
489 try
490 {
491 html = fs.readFileSync(SHARE_HTML_PATH, 'utf8');
492 }
493 catch
494 {
495 html = '<!DOCTYPE html><html lang="en-GB"><head><meta charset="UTF-8" /></head><body></body></html>';
496 }
497
498 html = html.replace(
499 '<title>Shared file</title>',
500 `<title>${ogEsc(pageTitle)}</title>\n ${ogBlock}`,
501 );
502
503 return html;
504}
505
506module.exports = router;
507module.exports.buildZip = buildZip;
508module.exports.pruneZipCache = pruneZipCache;
509module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
510module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;