-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
781 lines (723 loc) · 26.6 KB
/
Copy pathserver.js
File metadata and controls
781 lines (723 loc) · 26.6 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
'use strict';
const crypto = require('node:crypto');
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const path = require('node:path');
const Database = require('better-sqlite3');
const dotenv = require('dotenv');
const express = require('express');
const mime = require('mime-types');
const multer = require('multer');
dotenv.config({ path: path.join(__dirname, '.env') });
const PROJECT_ROOT = __dirname;
const HOST = process.env.HOST || '0.0.0.0';
const PORT = Number.parseInt(process.env.PORT || '3010', 10);
const UPLOAD_TOKEN = process.env.UPLOAD_TOKEN || '';
const ADMIN_TOKEN = process.env.ADMIN_TOKEN || '';
const DEFAULT_UPLOAD_TOKEN = 'change-me-upload-token';
const DEFAULT_ADMIN_TOKEN = 'change-me-admin-token';
const parsedMaxFileSize = Number.parseFloat(process.env.MAX_FILE_SIZE_MB || '200');
const MAX_FILE_SIZE_MB = Number.isFinite(parsedMaxFileSize) && parsedMaxFileSize > 0
? parsedMaxFileSize
: 200;
const MAX_FILE_SIZE_BYTES = Math.floor(MAX_FILE_SIZE_MB * 1024 * 1024);
const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
const PUBLIC_BASE_URL = process.env.PUBLIC_BASE_URL?.trim() || '';
const AUTO_CLEANUP_ENABLED = /^true$/i.test(process.env.AUTO_CLEANUP_ENABLED || 'false');
const parsedCleanupDays = Number.parseFloat(process.env.AUTO_CLEANUP_DAYS || '30');
const AUTO_CLEANUP_DAYS = Number.isFinite(parsedCleanupDays) && parsedCleanupDays > 0
? parsedCleanupDays
: 30;
const parsedCleanupInterval = Number.parseFloat(process.env.AUTO_CLEANUP_INTERVAL_HOURS || '12');
const AUTO_CLEANUP_INTERVAL_HOURS = Number.isFinite(parsedCleanupInterval) && parsedCleanupInterval > 0
? parsedCleanupInterval
: 12;
function resolveProjectPath(configuredPath, fallback) {
const value = configuredPath || fallback;
return path.isAbsolute(value) ? path.resolve(value) : path.resolve(PROJECT_ROOT, value);
}
const STORAGE_DIR = resolveProjectPath(process.env.STORAGE_DIR, 'storage');
const DATABASE_PATH = resolveProjectPath(process.env.DATABASE_PATH, 'data/clawdrop.sqlite');
fs.mkdirSync(STORAGE_DIR, { recursive: true });
fs.mkdirSync(path.dirname(DATABASE_PATH), { recursive: true });
const db = new Database(DATABASE_PATH);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
db.exec(`
CREATE TABLE IF NOT EXISTS files (
id TEXT PRIMARY KEY,
stored_name TEXT NOT NULL UNIQUE,
original_name TEXT NOT NULL,
size INTEGER NOT NULL,
mime_type TEXT NOT NULL,
sha256 TEXT NOT NULL,
uploaded_at TEXT NOT NULL,
download_count INTEGER NOT NULL DEFAULT 0,
deleted_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_files_uploaded_at
ON files (uploaded_at DESC);
CREATE TABLE IF NOT EXISTS share_links (
id TEXT PRIMARY KEY,
file_id TEXT NOT NULL,
token TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL,
expires_at TEXT,
max_downloads INTEGER,
download_count INTEGER NOT NULL DEFAULT 0,
revoked_at TEXT,
FOREIGN KEY (file_id) REFERENCES files(id)
);
CREATE INDEX IF NOT EXISTS idx_share_links_token ON share_links(token);
CREATE INDEX IF NOT EXISTS idx_share_links_file_id ON share_links(file_id);
CREATE INDEX IF NOT EXISTS idx_share_links_expires_at ON share_links(expires_at);
`);
function warnAboutToken(name, value, defaultValue) {
if (!value) {
console.warn(`[security] ${name} is not configured; its protected endpoints will reject all requests.`);
} else if (value === defaultValue) {
console.warn(`[security] ${name} still uses the example value. Replace it before deployment.`);
} else if (value.length < 32) {
console.warn(`[security] ${name} is short. Use a random token of at least 32 characters.`);
}
}
warnAboutToken('UPLOAD_TOKEN', UPLOAD_TOKEN, DEFAULT_UPLOAD_TOKEN);
warnAboutToken('ADMIN_TOKEN', ADMIN_TOKEN, DEFAULT_ADMIN_TOKEN);
if (UPLOAD_TOKEN && ADMIN_TOKEN && UPLOAD_TOKEN === ADMIN_TOKEN) {
console.warn('[security] UPLOAD_TOKEN and ADMIN_TOKEN are identical. Use separate values.');
}
function tokensMatch(received, expected) {
if (!received || !expected) return false;
const receivedHash = crypto.createHash('sha256').update(received, 'utf8').digest();
const expectedHash = crypto.createHash('sha256').update(expected, 'utf8').digest();
return crypto.timingSafeEqual(receivedHash, expectedHash);
}
function tokenGuard(expectedToken) {
return (req, res, next) => {
const match = /^Bearer\s+(.+)$/i.exec(req.get('authorization') || '');
if (!match || !tokensMatch(match[1], expectedToken)) {
return res.status(401).json({ ok: false, error: 'Unauthorized' });
}
return next();
};
}
const requireUploadToken = tokenGuard(UPLOAD_TOKEN);
const requireAdminToken = tokenGuard(ADMIN_TOKEN);
function normalizeOriginalName(input) {
const normalized = String(input || '').replace(/\\/g, '/');
const base = path.posix.basename(normalized).replace(/[\u0000-\u001f\u007f]/g, '').trim();
return (base || 'file').slice(0, 255);
}
function safeStoredPath(storedName) {
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(storedName)) {
return null;
}
const resolved = path.resolve(STORAGE_DIR, storedName);
if (path.dirname(resolved) !== STORAGE_DIR) return null;
return resolved;
}
const upload = multer({
storage: multer.diskStorage({
destination: (_req, _file, callback) => callback(null, STORAGE_DIR),
filename: (_req, file, callback) => {
const id = crypto.randomUUID();
file.clawdropId = id;
callback(null, id);
}
}),
limits: {
files: 1,
fileSize: MAX_FILE_SIZE_BYTES
}
});
const activeFileColumns = `
id,
stored_name AS storedName,
original_name AS originalName,
size,
mime_type AS mimeType,
sha256,
uploaded_at AS uploadedAt,
download_count AS downloadCount
`;
const getActiveFile = db.prepare(`
SELECT ${activeFileColumns}
FROM files
WHERE id = ? AND deleted_at IS NULL
`);
const listActiveFiles = db.prepare(`
SELECT ${activeFileColumns}
FROM files
WHERE deleted_at IS NULL
ORDER BY uploaded_at DESC
`);
const listFilesOlderThan = db.prepare(`
SELECT ${activeFileColumns}
FROM files
WHERE deleted_at IS NULL AND uploaded_at < ?
ORDER BY uploaded_at ASC
`);
const insertFile = db.prepare(`
INSERT INTO files (
id, stored_name, original_name, size, mime_type, sha256, uploaded_at
) VALUES (
@id, @storedName, @originalName, @size, @mimeType, @sha256, @uploadedAt
)
`);
const incrementDownloadCount = db.prepare(`
UPDATE files
SET download_count = download_count + 1
WHERE id = ? AND deleted_at IS NULL
`);
const decrementDownloadCount = db.prepare(`
UPDATE files
SET download_count = MAX(download_count - 1, 0)
WHERE id = ? AND deleted_at IS NULL
`);
const softDeleteFile = db.prepare(`
UPDATE files
SET deleted_at = ?
WHERE id = ? AND deleted_at IS NULL
`);
const revokeShare = db.prepare(`
UPDATE share_links
SET revoked_at = ?
WHERE id = ? AND revoked_at IS NULL
`);
const revokeSharesByFile = db.prepare(`
UPDATE share_links
SET revoked_at = ?
WHERE file_id = ? AND revoked_at IS NULL
`);
const softDeleteFileAndShares = db.transaction((deletedAt, fileId) => {
softDeleteFile.run(deletedAt, fileId);
revokeSharesByFile.run(deletedAt, fileId);
});
const insertShare = db.prepare(`
INSERT INTO share_links (
id, file_id, token, created_at, expires_at, max_downloads
) VALUES (
@id, @fileId, @token, @createdAt, @expiresAt, @maxDownloads
)
`);
const listActiveSharesByFile = db.prepare(`
SELECT
id,
file_id AS fileId,
token,
created_at AS createdAt,
expires_at AS expiresAt,
max_downloads AS maxDownloads,
download_count AS downloadCount,
revoked_at AS revokedAt
FROM share_links
WHERE file_id = ? AND revoked_at IS NULL
ORDER BY created_at DESC
`);
const getShareByToken = db.prepare(`
SELECT
share_links.id,
share_links.file_id AS fileId,
share_links.token,
share_links.created_at AS createdAt,
share_links.expires_at AS expiresAt,
share_links.max_downloads AS maxDownloads,
share_links.download_count AS downloadCount,
share_links.revoked_at AS revokedAt,
files.stored_name AS storedName,
files.original_name AS originalName,
files.size,
files.mime_type AS mimeType,
files.deleted_at AS fileDeletedAt
FROM share_links
JOIN files ON files.id = share_links.file_id
WHERE share_links.token = ?
`);
const incrementShareDownload = db.prepare(`
UPDATE share_links
SET download_count = download_count + 1
WHERE id = ?
`);
const decrementShareDownload = db.prepare(`
UPDATE share_links
SET download_count = MAX(download_count - 1, 0)
WHERE id = ?
`);
const claimShareDownload = db.transaction((token) => {
const share = getShareByToken.get(token);
const availability = shareAvailability(share);
if (availability !== 'active') return { availability, share };
incrementShareDownload.run(share.id);
incrementDownloadCount.run(share.fileId);
share.downloadCount += 1;
return { availability: 'active', share };
});
const releaseShareDownload = db.transaction((share) => {
decrementShareDownload.run(share.id);
decrementDownloadCount.run(share.fileId);
});
function publicFile(file) {
return {
id: file.id,
originalName: file.originalName,
size: file.size,
mimeType: file.mimeType,
sha256: file.sha256,
uploadedAt: file.uploadedAt,
downloadCount: file.downloadCount,
downloadUrl: `/api/files/${file.id}/download`,
previewUrl: `/api/files/${file.id}/preview`
};
}
function publicBaseUrl(req) {
if (PUBLIC_BASE_URL) {
try {
const configured = new URL(PUBLIC_BASE_URL);
if (configured.protocol === 'http:' || configured.protocol === 'https:') {
return configured.href.replace(/\/$/, '');
}
} catch {
// Fall back to the current request origin when configuration is invalid.
}
}
return `${req.protocol}://${req.get('host')}`;
}
function publicShare(share, req) {
const url = `/s/${share.token}`;
const now = Date.now();
return {
id: share.id,
fileId: share.fileId,
url,
fullUrl: `${publicBaseUrl(req)}${url}`,
createdAt: share.createdAt,
expiresAt: share.expiresAt,
maxDownloads: share.maxDownloads,
downloadCount: share.downloadCount || 0,
revokedAt: share.revokedAt || null,
isExpired: Boolean(share.expiresAt && Date.parse(share.expiresAt) <= now),
isLimitReached: share.maxDownloads !== null
&& share.downloadCount >= share.maxDownloads
};
}
function shareAvailability(share) {
if (!share || share.fileDeletedAt) return 'missing';
if (share.revokedAt) return 'revoked';
if (share.expiresAt && Date.parse(share.expiresAt) <= Date.now()) return 'expired';
if (share.maxDownloads !== null && share.downloadCount >= share.maxDownloads) return 'limited';
return 'active';
}
function escapeHtml(value) {
return String(value)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const unit = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
const value = bytes / (1024 ** unit);
return `${value >= 10 || unit === 0 ? value.toFixed(0) : value.toFixed(2)} ${units[unit]}`;
}
function sendSharePage(res, { statusCode, title, message, share = null }) {
const active = share && statusCode === 200;
const remaining = active && share.maxDownloads !== null
? Math.max(share.maxDownloads - share.downloadCount, 0)
: null;
const details = active
? `<dl class="share-details">
<div><dt>文件大小</dt><dd>${escapeHtml(formatFileSize(share.size))}</dd></div>
<div><dt>文件类型</dt><dd>${escapeHtml(share.mimeType)}</dd></div>
<div><dt>过期时间</dt><dd>${escapeHtml(share.expiresAt || '不限')}</dd></div>
<div><dt>剩余下载</dt><dd>${remaining === null ? '不限次数' : `${remaining} 次`}</dd></div>
</dl>`
: '';
const action = active
? `<a class="share-download" href="/s/${encodeURIComponent(share.token)}/download">下载文件</a>`
: '<a class="share-secondary" href="/">返回 ClawDrop</a>';
res.status(statusCode).type('html').send(`<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<meta name="theme-color" content="#f3f6fb">
<title>${escapeHtml(title)} · ClawDrop</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/share.css">
</head>
<body>
<main class="share-shell">
<section class="share-card">
<div class="share-brand"><span class="share-mark" aria-hidden="true">◆</span>ClawDrop</div>
<p class="share-label">临时文件分享</p>
<h1>${escapeHtml(title)}</h1>
<p class="share-message">${escapeHtml(message)}</p>
${details}
<div class="share-actions">${action}</div>
<p class="share-footnote">此页面只提供当前文件,不包含文件列表或管理权限。</p>
</section>
</main>
</body>
</html>`);
}
async function sha256File(filePath) {
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(filePath);
for await (const chunk of stream) hash.update(chunk);
return hash.digest('hex');
}
async function fileExists(filePath) {
try {
await fsp.access(filePath, fs.constants.R_OK);
return true;
} catch {
return false;
}
}
async function runCleanup({ olderThanDays, dryRun }) {
const cutoff = new Date(Date.now() - olderThanDays * 24 * 60 * 60 * 1000).toISOString();
const files = listFilesOlderThan.all(cutoff);
const result = {
ok: true,
dryRun,
matched: files.length,
deleted: 0,
failed: 0
};
if (!dryRun) {
for (const file of files) {
const filePath = safeStoredPath(file.storedName);
if (!filePath) {
result.failed += 1;
continue;
}
try {
await fsp.unlink(filePath).catch((error) => {
if (error.code !== 'ENOENT') throw error;
});
softDeleteFileAndShares(new Date().toISOString(), file.id);
result.deleted += 1;
} catch {
result.failed += 1;
}
}
}
console.log(`[cleanup] dryRun=${dryRun} matched=${result.matched} deleted=${result.deleted} failed=${result.failed}`);
return result;
}
const app = express();
app.disable('x-powered-by');
app.use((_req, res, next) => {
res.set({
'Content-Security-Policy': "default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; img-src 'self' blob: data:; frame-src blob:; script-src 'self'; style-src 'self'; connect-src 'self'",
'Referrer-Policy': 'no-referrer',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY'
});
next();
});
app.use(express.json({ limit: '16kb' }));
app.get('/api/health', async (_req, res) => {
const storageReady = await fileExists(STORAGE_DIR);
let databaseReady = false;
try {
databaseReady = db.prepare('SELECT 1 AS ready').get().ready === 1;
} catch {
databaseReady = false;
}
res.json({
ok: storageReady && databaseReady,
name: 'clawdrop',
time: new Date().toISOString(),
storageReady,
databaseReady
});
});
app.post('/api/upload', requireUploadToken, (req, res, next) => {
upload.single('file')(req, res, async (uploadError) => {
if (uploadError) {
if (uploadError instanceof multer.MulterError && uploadError.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({
ok: false,
error: `File exceeds the ${MAX_FILE_SIZE_MB} MB limit`
});
}
return res.status(400).json({ ok: false, error: 'Invalid file upload' });
}
if (!req.file) {
return res.status(400).json({ ok: false, error: 'A single file field named "file" is required' });
}
const filePath = safeStoredPath(req.file.filename);
if (!filePath) {
await fsp.unlink(req.file.path).catch(() => {});
return res.status(400).json({ ok: false, error: 'Invalid stored file name' });
}
try {
const originalName = normalizeOriginalName(req.file.originalname);
const record = {
id: req.file.clawdropId,
storedName: req.file.filename,
originalName,
size: req.file.size,
mimeType: mime.lookup(originalName) || 'application/octet-stream',
sha256: await sha256File(filePath),
uploadedAt: new Date().toISOString(),
downloadCount: 0
};
insertFile.run(record);
return res.status(201).json({ ok: true, file: publicFile(record) });
} catch (error) {
await fsp.unlink(filePath).catch(() => {});
return next(error);
}
});
});
app.post('/api/admin/cleanup', requireAdminToken, async (req, res) => {
const olderThanDays = req.body?.olderThanDays === undefined
? AUTO_CLEANUP_DAYS
: req.body.olderThanDays;
const dryRun = req.body?.dryRun === undefined ? true : req.body.dryRun;
if (!Number.isFinite(olderThanDays) || olderThanDays < 1 || olderThanDays > 3650) {
return res.status(400).json({ ok: false, error: 'olderThanDays must be a number from 1 to 3650' });
}
if (typeof dryRun !== 'boolean') {
return res.status(400).json({ ok: false, error: 'dryRun must be a boolean' });
}
return res.json(await runCleanup({ olderThanDays, dryRun }));
});
app.get('/api/files', requireAdminToken, (_req, res) => {
res.json({ ok: true, files: listActiveFiles.all().map(publicFile) });
});
app.get('/api/files/:id', requireAdminToken, (req, res) => {
const file = getActiveFile.get(req.params.id);
if (!file) return res.status(404).json({ ok: false, error: 'File not found' });
return res.json({ ok: true, file: publicFile(file) });
});
app.post('/api/files/:id/share', requireAdminToken, (req, res) => {
const file = getActiveFile.get(req.params.id);
if (!file) return res.status(404).json({ ok: false, error: 'File not found' });
const expiresInHours = req.body?.expiresInHours === undefined
? 24
: req.body.expiresInHours;
const maxDownloads = req.body?.maxDownloads === undefined
? null
: req.body.maxDownloads;
if (!Number.isInteger(expiresInHours) || expiresInHours < 1 || expiresInHours > 168) {
return res.status(400).json({ ok: false, error: 'expiresInHours must be an integer from 1 to 168' });
}
if (maxDownloads !== null
&& (!Number.isInteger(maxDownloads) || maxDownloads < 1 || maxDownloads > 100)) {
return res.status(400).json({ ok: false, error: 'maxDownloads must be null or an integer from 1 to 100' });
}
const createdAt = new Date();
const share = {
id: crypto.randomUUID(),
fileId: file.id,
token: crypto.randomBytes(32).toString('base64url'),
createdAt: createdAt.toISOString(),
expiresAt: new Date(createdAt.getTime() + expiresInHours * 60 * 60 * 1000).toISOString(),
maxDownloads,
downloadCount: 0,
revokedAt: null
};
insertShare.run(share);
return res.status(201).json({ ok: true, share: publicShare(share, req) });
});
app.get('/api/files/:id/shares', requireAdminToken, (req, res) => {
const file = getActiveFile.get(req.params.id);
if (!file) return res.status(404).json({ ok: false, error: 'File not found' });
const shares = listActiveSharesByFile.all(file.id).map((share) => publicShare(share, req));
return res.json({ ok: true, shares });
});
app.delete('/api/shares/:id', requireAdminToken, (req, res) => {
const result = revokeShare.run(new Date().toISOString(), req.params.id);
if (result.changes === 0) {
return res.status(404).json({ ok: false, error: 'Share not found' });
}
return res.json({ ok: true });
});
app.get('/s/:token', async (req, res) => {
const share = /^[A-Za-z0-9_-]{43,}$/.test(req.params.token)
? getShareByToken.get(req.params.token)
: null;
const availability = shareAvailability(share);
if (availability === 'missing') {
return sendSharePage(res, {
statusCode: 404,
title: '分享链接不存在',
message: '这个分享链接无效,或对应文件已不可用。'
});
}
if (availability === 'revoked') {
return sendSharePage(res, { statusCode: 410, title: '链接已失效', message: '分享者已撤销这个链接。' });
}
if (availability === 'expired') {
return sendSharePage(res, { statusCode: 410, title: '链接已过期', message: '这个临时分享已超过有效期。' });
}
if (availability === 'limited') {
return sendSharePage(res, { statusCode: 410, title: '下载次数已用完', message: '这个分享链接已达到下载次数上限。' });
}
const filePath = safeStoredPath(share.storedName);
if (!filePath || !(await fileExists(filePath))) {
return sendSharePage(res, {
statusCode: 404,
title: '分享文件不可用',
message: '文件已被删除或暂时无法访问。'
});
}
return sendSharePage(res, {
statusCode: 200,
title: share.originalName,
message: '此文件由 ClawDrop 临时分享。',
share
});
});
app.get('/s/:token/download', async (req, res, next) => {
const token = /^[A-Za-z0-9_-]{43,}$/.test(req.params.token)
? req.params.token
: null;
const initialShare = token ? getShareByToken.get(token) : null;
const initialAvailability = shareAvailability(initialShare);
if (initialAvailability === 'missing') {
return sendSharePage(res, { statusCode: 404, title: '分享链接不存在', message: '这个分享链接无效,或对应文件已不可用。' });
}
if (initialAvailability === 'revoked') {
return sendSharePage(res, { statusCode: 410, title: '链接已失效', message: '分享者已撤销这个链接。' });
}
if (initialAvailability === 'expired') {
return sendSharePage(res, { statusCode: 410, title: '链接已过期', message: '这个临时分享已超过有效期。' });
}
if (initialAvailability === 'limited') {
return sendSharePage(res, { statusCode: 410, title: '下载次数已用完', message: '这个分享链接已达到下载次数上限。' });
}
const filePath = safeStoredPath(initialShare.storedName);
if (!filePath || !(await fileExists(filePath))) {
return sendSharePage(res, { statusCode: 404, title: '分享文件不可用', message: '文件已被删除或暂时无法访问。' });
}
const claimed = claimShareDownload(token);
if (claimed.availability !== 'active') {
const messages = {
missing: ['分享链接不存在', '这个分享链接无效,或对应文件已不可用。'],
revoked: ['链接已失效', '分享者已撤销这个链接。'],
expired: ['链接已过期', '这个临时分享已超过有效期。'],
limited: ['下载次数已用完', '这个分享链接已达到下载次数上限。']
};
const [title, message] = messages[claimed.availability];
return sendSharePage(res, { statusCode: claimed.availability === 'missing' ? 404 : 410, title, message });
}
return res.download(filePath, normalizeOriginalName(claimed.share.originalName), (error) => {
if (error) {
releaseShareDownload(claimed.share);
if (!res.headersSent) next(error);
}
});
});
app.get('/api/files/:id/download', requireAdminToken, async (req, res, next) => {
const file = getActiveFile.get(req.params.id);
const filePath = file && safeStoredPath(file.storedName);
if (!file || !filePath || !(await fileExists(filePath))) {
return res.status(404).json({ ok: false, error: 'File not found' });
}
return res.download(filePath, normalizeOriginalName(file.originalName), (error) => {
if (!error) {
incrementDownloadCount.run(file.id);
} else if (!res.headersSent) {
next(error);
}
});
});
const imagePreviewTypes = new Map([
['.png', 'image/png'],
['.jpg', 'image/jpeg'],
['.jpeg', 'image/jpeg'],
['.gif', 'image/gif'],
['.webp', 'image/webp']
]);
const textPreviewExtensions = new Set([
'.txt', '.log', '.md', '.json', '.js', '.css', '.html', '.htm'
]);
app.get('/api/files/:id/preview', requireAdminToken, async (req, res) => {
const file = getActiveFile.get(req.params.id);
const filePath = file && safeStoredPath(file.storedName);
if (!file || !filePath || !(await fileExists(filePath))) {
return res.status(404).json({ ok: false, error: 'File not found' });
}
const extension = path.extname(file.originalName).toLowerCase();
const inlineName = normalizeOriginalName(file.originalName).replace(/["\\]/g, '_');
res.set('Content-Disposition', `inline; filename="${inlineName}"`);
if (imagePreviewTypes.has(extension)) {
res.type(imagePreviewTypes.get(extension));
return res.sendFile(filePath);
}
if (extension === '.pdf') {
res.type('application/pdf');
return res.sendFile(filePath);
}
if (textPreviewExtensions.has(extension)) {
if (file.size > MAX_TEXT_PREVIEW_BYTES) {
return res.status(413).json({ ok: false, error: 'Text preview is limited to 2 MB' });
}
res.type('text/plain; charset=utf-8');
return res.sendFile(filePath);
}
return res.status(415).json({ ok: false, error: 'Preview is not supported for this file type' });
});
app.delete('/api/files/:id', requireAdminToken, async (req, res, next) => {
const file = getActiveFile.get(req.params.id);
const filePath = file && safeStoredPath(file.storedName);
if (!file || !filePath) {
return res.status(404).json({ ok: false, error: 'File not found' });
}
try {
await fsp.unlink(filePath);
softDeleteFileAndShares(new Date().toISOString(), file.id);
return res.json({ ok: true });
} catch (error) {
if (error && error.code === 'ENOENT') {
return res.status(404).json({ ok: false, error: 'File not found' });
}
return next(error);
}
});
app.use(express.static(path.join(PROJECT_ROOT, 'public'), {
dotfiles: 'deny',
index: 'index.html',
maxAge: 0
}));
app.use('/api', (_req, res) => {
res.status(404).json({ ok: false, error: 'Not found' });
});
app.use((_error, req, res, _next) => {
if (process.env.NODE_ENV !== 'test') {
console.error(`[error] Request failed: ${req.method} ${req.originalUrl}`);
}
if (!res.headersSent) {
res.status(500).json({ ok: false, error: 'Internal server error' });
}
});
const server = app.listen(PORT, HOST, () => {
console.log(`ClawDrop listening on http://${HOST}:${PORT}`);
});
let cleanupTimer = null;
if (AUTO_CLEANUP_ENABLED) {
cleanupTimer = setInterval(() => {
runCleanup({ olderThanDays: AUTO_CLEANUP_DAYS, dryRun: false }).catch(() => {
console.error('[cleanup] scheduled cleanup failed');
});
}, AUTO_CLEANUP_INTERVAL_HOURS * 60 * 60 * 1000);
cleanupTimer.unref();
console.log(`[cleanup] enabled days=${AUTO_CLEANUP_DAYS} intervalHours=${AUTO_CLEANUP_INTERVAL_HOURS}`);
}
function shutdown() {
if (cleanupTimer) clearInterval(cleanupTimer);
server.close(() => {
db.close();
process.exit(0);
});
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);