BlueGit

timfa filemanager

Files

filemanager / server / routes / share.js

share.js

share.js 8.4 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');
13
14const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
15const ZIP_CACHE_DIR = path.join(__dirname, '../../zip-cache');
16const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
17
18// ---------------------------------------------------------------------------
19// Helpers
20// ---------------------------------------------------------------------------
21
22function effectivePaths ()
23{
24 return getEffectivePaths(loadConfig().paths || []);
25}
26
27/** Returns the configured root that contains absPath, or null. */
28function resolveRoot (absPath)
29{
30 return getAllowedRoot(absPath, effectivePaths());
31}
32
33/** Generate a cryptographically random token. */
34function generateToken ()
35{
36 return crypto.randomBytes(32).toString('hex');
37}
38
39/** Ensure the zip cache directory exists. */
40function ensureZipCacheDir ()
41{
42 if (!fs.existsSync(ZIP_CACHE_DIR))
43 {
44 fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true });
45 }
46}
47
48/**
49 * Delete zip files in ZIP_CACHE_DIR that are older than ZIP_MAX_AGE_MS.
50 * Also delete zip files whose corresponding share token has expired.
51 */
52function pruneZipCache ()
53{
54 ensureZipCacheDir();
55 const now = Date.now();
56 let entries;
57 try
58 {
59 entries = fs.readdirSync(ZIP_CACHE_DIR);
60 } catch
61 {
62 return;
63 }
64
65 for (const name of entries)
66 {
67 if (!name.endsWith('.zip')) continue;
68 const fullPath = path.join(ZIP_CACHE_DIR, name);
69 try
70 {
71 const stat = fs.statSync(fullPath);
72 const age = now - stat.mtimeMs;
73 if (age > ZIP_MAX_AGE_MS)
74 {
75 fs.unlinkSync(fullPath);
76 }
77 } catch
78 {
79 // Ignore files that disappeared.
80 }
81 }
82}
83
84/**
85 * Create (or return cached) zip for the given directory.
86 * cacheKey is used as the filename stem.
87 * Returns the full path to the zip file.
88 */
89function buildZip (dirPath, cacheKey)
90{
91 return new Promise((resolve, reject) =>
92 {
93 ensureZipCacheDir();
94 pruneZipCache();
95
96 const zipPath = path.join(ZIP_CACHE_DIR, `${cacheKey}.zip`);
97
98 // Serve cached version if it exists and is not too old.
99 if (fs.existsSync(zipPath))
100 {
101 try
102 {
103 const stat = fs.statSync(zipPath);
104 if (Date.now() - stat.mtimeMs < ZIP_MAX_AGE_MS)
105 {
106 return resolve(zipPath);
107 }
108 fs.unlinkSync(zipPath);
109 } catch { /* fall through to rebuild */ }
110 }
111
112 const tmpPath = zipPath + '.tmp';
113 const output = fs.createWriteStream(tmpPath);
114 const archive = archiver('zip', { zlib: { level: 6 } });
115
116 output.on('close', () =>
117 {
118 try
119 {
120 fs.renameSync(tmpPath, zipPath);
121 resolve(zipPath);
122 } catch (err)
123 {
124 reject(err);
125 }
126 });
127
128 archive.on('error', (err) =>
129 {
130 try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
131 reject(err);
132 });
133
134 archive.pipe(output);
135 archive.directory(dirPath, path.basename(dirPath));
136 archive.finalize();
137 });
138}
139
140// ---------------------------------------------------------------------------
141// POST /api/share/create
142// Body: { filePath: <absolute-path> }
143// Authenticated. Creates a 24-hour share token for a file or directory.
144// ---------------------------------------------------------------------------
145router.post('/create', requireAuth, (req, res) =>
146{
147 const filePath = String((req.body && req.body.filePath) || '').trim();
148 if (!filePath)
149 {
150 return res.status(400).json({ error: 'filePath is required.' });
151 }
152
153 const root = resolveRoot(filePath);
154 if (!root)
155 {
156 return res.status(403).json({ error: 'Access denied.' });
157 }
158
159 // Verify the user can read that root.
160 const rootLabel = path.basename(root);
161 const user = req.user;
162 const canRead = user.isAdmin
163 || !!(user.permissions[rootLabel] && user.permissions[rootLabel].read);
164 if (!canRead)
165 {
166 return res.status(403).json({ error: 'Access denied.' });
167 }
168
169 let stat;
170 try
171 {
172 stat = fs.statSync(filePath);
173 } catch
174 {
175 return res.status(404).json({ error: 'File or folder not found.' });
176 }
177
178 const isDir = stat.isDirectory() ? 1 : 0;
179 const now = Date.now();
180 const expiresAt = now + SHARE_TTL_MS;
181 const token = generateToken();
182
183 const db = getDb();
184 db.prepare(`
185 INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at)
186 VALUES (?, ?, ?, ?, ?, ?)
187 `).run([token, filePath, isDir, user.username, now, expiresAt]);
188
189 res.json({ token, expiresAt });
190});
191
192// ---------------------------------------------------------------------------
193// GET /api/share/info/:token
194// Public (no auth). Returns metadata about the shared item.
195// ---------------------------------------------------------------------------
196router.get('/info/:token', (req, res) =>
197{
198 const token = String(req.params.token || '').trim();
199 if (!token) return res.status(400).json({ error: 'Token is required.' });
200
201 const db = getDb();
202 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
203
204 if (!row) return res.status(404).json({ error: 'Share link not found.' });
205 if (Date.now() > row.expires_at)
206 {
207 return res.status(410).json({ error: 'Share link has expired.' });
208 }
209
210 const name = path.basename(row.file_path);
211 res.json({
212 name,
213 isDir: !!row.is_dir,
214 expiresAt: row.expires_at,
215 });
216});
217
218// ---------------------------------------------------------------------------
219// GET /api/share/preview/:token
220// Public (no auth). Streams a file for inline preview (non-directory only).
221// ---------------------------------------------------------------------------
222router.get('/preview/:token', (req, res) =>
223{
224 const token = String(req.params.token || '').trim();
225 if (!token) return res.status(400).json({ error: 'Token is required.' });
226
227 const db = getDb();
228 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
229
230 if (!row) return res.status(404).json({ error: 'Share link not found.' });
231 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
232 if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' });
233
234 if (!fs.existsSync(row.file_path))
235 {
236 return res.status(404).json({ error: 'File not found.' });
237 }
238
239 // Limit preview size to 50 MB to prevent accidental large file streaming.
240 const MAX_PREVIEW_BYTES = 50 * 1024 * 1024;
241 let stat;
242 try { stat = fs.statSync(row.file_path); } catch { return res.status(404).json({ error: 'File not found.' }); }
243
244 if (stat.size > MAX_PREVIEW_BYTES)
245 {
246 return res.status(413).json({ error: 'File too large for inline preview.' });
247 }
248
249 res.set('Cache-Control', 'private, no-store');
250 res.sendFile(row.file_path);
251});
252
253// ---------------------------------------------------------------------------
254// GET /api/share/download/:token
255// Public (no auth). Streams the file or a zip of the directory.
256// ---------------------------------------------------------------------------
257router.get('/download/:token', async (req, res) =>
258{
259 const token = String(req.params.token || '').trim();
260 if (!token) return res.status(400).json({ error: 'Token is required.' });
261
262 const db = getDb();
263 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
264
265 if (!row) return res.status(404).json({ error: 'Share link not found.' });
266 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
267
268 if (row.is_dir)
269 {
270 if (!fs.existsSync(row.file_path) || !fs.statSync(row.file_path).isDirectory())
271 {
272 return res.status(404).json({ error: 'Directory not found.' });
273 }
274
275 try
276 {
277 const zipPath = await buildZip(row.file_path, token);
278 const zipName = `${path.basename(row.file_path)}.zip`;
279 res.download(zipPath, zipName);
280 } catch (err)
281 {
282 res.status(500).json({ error: 'Failed to create zip archive.' });
283 }
284 } else
285 {
286 if (!fs.existsSync(row.file_path))
287 {
288 return res.status(404).json({ error: 'File not found.' });
289 }
290
291 res.download(row.file_path, path.basename(row.file_path));
292 }
293});
294
295module.exports = router;
296module.exports.buildZip = buildZip;
297module.exports.pruneZipCache = pruneZipCache;
298module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;