-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1220 lines (1106 loc) · 45.9 KB
/
Copy pathserver.js
File metadata and controls
1220 lines (1106 loc) · 45.9 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
const http = require("http");
const { spawn } = require("child_process");
const fs = require("fs");
const fsp = require("fs/promises");
const os = require("os");
const path = require("path");
const crypto = require("crypto");
const { pipeline } = require("stream/promises");
loadEnv();
const PORT = Number(process.env.PORT || 8080);
const HOST = process.env.HOST || "127.0.0.1";
const NAS_NAME = process.env.NAS_NAME || "nas.local";
const USER = process.env.VAULT_USER || "usuario";
const PASS = process.env.VAULT_PASS || "change-this-password";
const PASS_SHA256 = String(process.env.VAULT_PASS_SHA256 || "").trim().toLowerCase();
const SESSION_TTL_MS = Number(process.env.SESSION_TTL_HOURS || 8) * 60 * 60 * 1000;
const LOGIN_WINDOW_MS = 10 * 60 * 1000;
const LOGIN_MAX_ATTEMPTS = Number(process.env.LOGIN_MAX_ATTEMPTS || 8);
const TEXT_LIMIT_BYTES = Number(process.env.TEXT_LIMIT_BYTES || 1024 * 1024);
const BACKEND_MODE = String(process.env.BACKEND_MODE || "local").trim().toLowerCase();
const SMB_HOST = process.env.SMB_HOST || "127.0.0.1";
const SMB_WORKGROUP = process.env.SMB_WORKGROUP || "";
const SMBCLIENT_BIN = process.env.SMBCLIENT_BIN || "smbclient";
const SMB_TIMEOUT_MS = Number(process.env.SMB_TIMEOUT_MS || 30000);
const TRASH_DIR = ".haze-trash";
const TRASH_MANIFEST = ".manifest.json";
const STORAGES = parseStorages(process.env.STORAGE_ROOTS || "public:./data/public,private:./data/private");
const sessions = new Map();
const loginAttempts = new Map();
async function main() {
if (BACKEND_MODE !== "smb") {
await Promise.all(STORAGES.map(async (storage) => {
await fsp.mkdir(storage.root, { recursive: true });
await ensureTrash(storage);
}));
}
const server = http.createServer((req, res) => {
handle(req, res).catch((error) => {
console.error(error);
sendJson(res, error.statusCode || 500, { error: error.publicMessage || "Error interno" });
});
});
server.listen(PORT, HOST, () => {
console.log(`Haze Vault listo en http://${HOST}:${PORT}`);
console.log(`NAS: ${NAS_NAME}`);
if (BACKEND_MODE === "smb") console.log(`SMB: //${SMB_HOST}`);
else for (const storage of STORAGES) console.log(`${storage.name}: ${storage.root}`);
});
}
async function handle(req, res) {
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
if (req.method === "GET" && url.pathname === "/") {
return sendFile(res, path.join(__dirname, "public", "index.html"), "text/html; charset=utf-8");
}
if (req.method === "GET" && url.pathname.startsWith("/assets/")) {
return serveAsset(res, url.pathname);
}
if (req.method === "GET" && url.pathname === "/api/status") {
return sendJson(res, 200, { nasName: NAS_NAME, online: true, backendMode: BACKEND_MODE });
}
if (req.method === "POST" && url.pathname === "/api/login") return login(req, res);
if (req.method === "POST" && url.pathname === "/api/logout") {
sessions.delete(getSessionId(req));
setCookie(res, "vault_session", "", "Max-Age=0; HttpOnly; SameSite=Lax");
return sendJson(res, 200, { ok: true });
}
const session = getSession(req);
if (!session) return sendJson(res, 401, { error: "No autorizado" });
if (req.method === "GET" && url.pathname === "/api/me") {
return sendJson(res, 200, { user: session.user || USER, nasName: NAS_NAME, online: true, backendMode: BACKEND_MODE });
}
if (BACKEND_MODE === "smb") return handleSmb(req, res, url, session);
if (req.method === "GET" && url.pathname === "/api/storages") return listStorages(res);
if (req.method === "GET" && url.pathname === "/api/storage-status") return storageStatus(res);
if (req.method === "GET" && url.pathname === "/api/files") return listFiles(res, url);
if (req.method === "PUT" && url.pathname === "/api/upload") return uploadFile(req, res, url);
if (req.method === "GET" && url.pathname === "/api/download") return downloadFile(req, res, url);
if (req.method === "GET" && url.pathname === "/api/preview") return previewFile(req, res, url);
if (req.method === "GET" && url.pathname === "/api/details") return detailsFile(res, url);
if (req.method === "GET" && url.pathname === "/api/text") return getTextFile(res, url);
if (req.method === "PUT" && url.pathname === "/api/text") return putTextFile(req, res, url);
if (req.method === "DELETE" && url.pathname === "/api/file") return trashFileUrl(res, url);
if (req.method === "POST" && url.pathname === "/api/delete-many") return trashMany(req, res);
if (req.method === "POST" && url.pathname === "/api/trash") return trashFile(req, res);
if (req.method === "POST" && url.pathname === "/api/trash-many") return trashMany(req, res);
if (req.method === "GET" && url.pathname === "/api/trash") return listTrash(res, url);
if (req.method === "POST" && url.pathname === "/api/restore") return restoreTrash(req, res);
if (req.method === "DELETE" && url.pathname === "/api/trash") return deleteTrash(req, res);
if (req.method === "POST" && url.pathname === "/api/folder") return createFolder(req, res);
if (req.method === "POST" && url.pathname === "/api/text-file") return createTextFile(req, res);
if (req.method === "POST" && url.pathname === "/api/rename") return renameItem(req, res);
if (req.method === "POST" && url.pathname === "/api/copy") return copyItem(req, res);
if (req.method === "POST" && url.pathname === "/api/move") return moveItem(req, res);
sendJson(res, 404, { error: "No encontrado" });
}
async function login(req, res) {
const ip = clientIp(req);
if (isLoginLimited(ip)) {
return sendJson(res, 429, { error: "Demasiados intentos. Espera unos minutos." });
}
const body = await readJson(req);
if (BACKEND_MODE === "smb") {
return smbLogin(req, res, body, ip);
}
if (body.user !== USER || !passwordMatches(body.password || "")) {
recordLoginFailure(ip);
return sendJson(res, 401, { error: "Usuario o contrasena incorrectos" });
}
loginAttempts.delete(ip);
const id = crypto.randomBytes(32).toString("hex");
sessions.set(id, { createdAt: Date.now(), expiresAt: Date.now() + SESSION_TTL_MS });
setCookie(res, "vault_session", id, `Max-Age=${Math.floor(SESSION_TTL_MS / 1000)}; HttpOnly; SameSite=Lax`);
sendJson(res, 200, { ok: true });
}
async function handleSmb(req, res, url, session) {
if (req.method === "GET" && url.pathname === "/api/storages") return smbListStorages(res, session);
if (req.method === "GET" && url.pathname === "/api/storage-status") return smbStorageStatus(res, session);
if (req.method === "GET" && url.pathname === "/api/files") return smbListFiles(res, url, session);
if (req.method === "PUT" && url.pathname === "/api/upload") return smbUploadFile(req, res, url, session);
if (req.method === "GET" && url.pathname === "/api/download") return smbDownloadFile(req, res, url, session);
if (req.method === "GET" && url.pathname === "/api/preview") return smbPreviewFile(req, res, url, session);
if (req.method === "GET" && url.pathname === "/api/details") return smbDetailsFile(res, url, session);
if (req.method === "GET" && url.pathname === "/api/text") return smbGetTextFile(res, url, session);
if (req.method === "PUT" && url.pathname === "/api/text") return smbPutTextFile(req, res, url, session);
if (req.method === "POST" && url.pathname === "/api/folder") return smbCreateFolder(req, res, session);
if (req.method === "POST" && url.pathname === "/api/text-file") return smbCreateTextFile(req, res, session);
if (req.method === "POST" && url.pathname === "/api/rename") return smbRenameItem(req, res, session);
if (req.method === "POST" && url.pathname === "/api/trash") return smbTrashFile(req, res, session);
if (req.method === "POST" && url.pathname === "/api/trash-many") return smbTrashMany(req, res, session);
if (req.method === "DELETE" && url.pathname === "/api/file") return smbTrashFileUrl(res, url, session);
if (req.method === "GET" && url.pathname === "/api/trash") return smbListTrash(res, url);
if (req.method === "POST" && url.pathname === "/api/restore") return sendJson(res, 501, { error: "Papelera SMB no soportada aun" });
if (req.method === "DELETE" && url.pathname === "/api/trash") return sendJson(res, 501, { error: "Papelera SMB no soportada aun" });
if (req.method === "POST" && url.pathname === "/api/copy") return sendJson(res, 501, { error: "Copiar en SMB no soportado aun" });
if (req.method === "POST" && url.pathname === "/api/move") return sendJson(res, 501, { error: "Mover en SMB no soportado aun" });
sendJson(res, 404, { error: "No encontrado" });
}
async function listStorages(res) {
const storages = await Promise.all(STORAGES.map(async (storage) => {
let count = 0;
try {
count = (await fsp.readdir(storage.root)).filter((name) => !name.startsWith(".")).length;
} catch {
count = 0;
}
return { id: storage.id, name: storage.name, count };
}));
sendJson(res, 200, { nasName: NAS_NAME, storages });
}
async function storageStatus(res) {
const storages = await Promise.all(STORAGES.map(async (storage) => {
const status = { id: storage.id, name: storage.name, root: storage.root, exists: false, writable: false, readonly: true };
try {
await fsp.access(storage.root, fs.constants.F_OK);
status.exists = true;
await fsp.access(storage.root, fs.constants.W_OK);
status.writable = true;
status.readonly = false;
} catch {}
if (typeof fsp.statfs === "function") {
try {
const stat = await fsp.statfs(storage.root);
status.total = Number(stat.blocks) * Number(stat.bsize);
status.free = Number(stat.bavail) * Number(stat.bsize);
} catch {}
}
return status;
}));
sendJson(res, 200, { nasName: NAS_NAME, storages });
}
async function listFiles(res, url) {
const { storage, rel } = resolveRequestPath(url);
const entries = await fsp.readdir(rel.fullPath, { withFileTypes: true });
const items = await Promise.all(entries
.filter((entry) => !entry.name.startsWith(".") && entry.name !== TRASH_DIR)
.map(async (entry) => fileInfo(storage, rel.relative, entry.name, path.join(rel.fullPath, entry.name), entry)));
sendJson(res, 200, {
nasName: NAS_NAME,
storage: { id: storage.id, name: storage.name },
path: rel.relative,
parent: parentRel(rel.relative),
items: sortItems(items, "name")
});
}
async function uploadFile(req, res, url) {
const storage = getStorage(url.searchParams.get("storage"));
const folder = sanitizeRel(url.searchParams.get("path") || "");
const rawName = url.searchParams.get("name") || req.headers["x-file-name"] || "archivo";
const fileName = sanitizeName(String(rawName));
const targetDir = resolveInside(storage.root, folder);
const targetPath = await availablePath(resolveInside(targetDir, fileName));
await fsp.mkdir(targetDir, { recursive: true });
await pipeline(req, fs.createWriteStream(targetPath, { flags: "w" }));
sendJson(res, 200, { ok: true, name: path.basename(targetPath) });
}
async function downloadFile(req, res, url) {
const { rel } = resolveRequestPath(url);
const stat = await fsp.stat(rel.fullPath);
if (!stat.isFile()) return sendJson(res, 400, { error: "No es archivo" });
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Length": stat.size,
"Content-Disposition": `attachment; filename="${encodeURIComponent(path.basename(rel.fullPath))}"`
});
fs.createReadStream(rel.fullPath).pipe(res);
}
async function previewFile(req, res, url) {
const { rel } = resolveRequestPath(url);
const stat = await fsp.stat(rel.fullPath);
if (!stat.isFile()) return sendJson(res, 400, { error: "No es archivo" });
const ext = path.extname(rel.fullPath).toLowerCase();
const types = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".gif": "image/gif",
".mp4": "video/mp4",
".m4v": "video/mp4",
".webm": "video/webm",
".mov": "video/quicktime"
};
if (!types[ext]) return sendJson(res, 415, { error: "Sin vista previa" });
const range = req.headers.range;
if (range) return streamRange(res, rel.fullPath, stat.size, types[ext], range);
res.writeHead(200, {
"Accept-Ranges": "bytes",
"Content-Type": types[ext],
"Content-Length": stat.size,
"Cache-Control": "private, max-age=60"
});
fs.createReadStream(rel.fullPath).pipe(res);
}
function streamRange(res, filePath, size, contentType, range) {
const match = /^bytes=(\d*)-(\d*)$/.exec(range);
if (!match) {
res.writeHead(416, { "Content-Range": `bytes */${size}` });
res.end();
return;
}
let start = match[1] ? Number(match[1]) : 0;
let end = match[2] ? Number(match[2]) : size - 1;
if (!match[1] && match[2]) {
const suffixLength = Number(match[2]);
start = Math.max(size - suffixLength, 0);
end = size - 1;
}
if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start < 0 || end >= size) {
res.writeHead(416, { "Content-Range": `bytes */${size}` });
res.end();
return;
}
res.writeHead(206, {
"Accept-Ranges": "bytes",
"Content-Type": contentType,
"Content-Length": end - start + 1,
"Content-Range": `bytes ${start}-${end}/${size}`,
"Cache-Control": "private, max-age=60"
});
fs.createReadStream(filePath, { start, end }).pipe(res);
}
async function detailsFile(res, url) {
const { storage, rel } = resolveRequestPath(url);
const info = await detailInfo(storage, rel.relative, rel.fullPath);
sendJson(res, 200, { item: info });
}
async function getTextFile(res, url) {
const { rel } = resolveRequestPath(url);
const stat = await fsp.stat(rel.fullPath);
if (!stat.isFile()) return sendJson(res, 400, { error: "No es archivo" });
if (stat.size > TEXT_LIMIT_BYTES) return sendJson(res, 413, { error: "Archivo demasiado grande para editar" });
const content = await fsp.readFile(rel.fullPath, "utf8");
sendJson(res, 200, { content });
}
async function putTextFile(req, res, url) {
const { rel } = resolveRequestPath(url);
const body = await readJson(req, TEXT_LIMIT_BYTES + 4096);
const stat = await fsp.stat(rel.fullPath);
if (!stat.isFile()) return sendJson(res, 400, { error: "No es archivo" });
await fsp.writeFile(rel.fullPath, String(body.content || ""), "utf8");
sendJson(res, 200, { ok: true });
}
async function trashFileUrl(res, url) {
const { storage, rel } = resolveRequestPath(url);
const trashed = await moveToTrash(storage, rel.relative);
sendJson(res, 200, { ok: true, trashed });
}
async function trashFile(req, res) {
const body = await readJson(req);
const storage = getStorage(body.storage);
const trashed = await moveToTrash(storage, body.path || "");
sendJson(res, 200, { ok: true, trashed });
}
async function trashMany(req, res) {
const body = await readJson(req);
const storage = getStorage(body.storage);
const paths = Array.isArray(body.paths) ? body.paths : [];
const trashed = [];
for (const itemPath of paths) {
const moved = await moveToTrash(storage, itemPath).catch(() => null);
if (moved) trashed.push(moved);
}
sendJson(res, 200, { ok: true, count: trashed.length, trashed });
}
async function listTrash(res, url) {
const storage = getStorage(url.searchParams.get("storage"));
await ensureTrash(storage);
const manifest = await readTrashManifest(storage);
const items = [];
for (const [trashPath, meta] of Object.entries(manifest.items || {})) {
const fullPath = trashPathToFull(storage, trashPath);
const stat = await fsp.stat(fullPath).catch(() => null);
if (!stat) continue;
items.push({
name: path.basename(trashPath),
path: trashPath,
originalPath: meta.originalPath || "",
deletedAt: meta.deletedAt || "",
type: stat.isDirectory() ? "folder" : "file",
kind: classifyName(path.basename(trashPath), stat.isDirectory()),
size: stat.size,
modified: stat.mtime.toISOString()
});
}
items.sort((a, b) => String(b.deletedAt).localeCompare(String(a.deletedAt)));
sendJson(res, 200, { storage: { id: storage.id, name: storage.name }, items });
}
async function restoreTrash(req, res) {
const body = await readJson(req);
const storage = getStorage(body.storage);
const trashPath = sanitizeTrashRel(body.path || "");
const source = trashPathToFull(storage, trashPath);
const manifest = await readTrashManifest(storage);
const meta = manifest.items[trashPath] || {};
const original = sanitizeRel(meta.originalPath || path.basename(trashPath));
const target = await availablePath(resolveInside(storage.root, original));
await fsp.mkdir(path.dirname(target), { recursive: true });
await fsp.rename(source, target);
delete manifest.items[trashPath];
await writeTrashManifest(storage, manifest);
sendJson(res, 200, { ok: true, path: path.relative(storage.root, target).split(path.sep).join("/") });
}
async function deleteTrash(req, res) {
const body = await readJson(req);
const storage = getStorage(body.storage);
const manifest = await readTrashManifest(storage);
const paths = Array.isArray(body.paths) ? body.paths : [body.path].filter(Boolean);
let count = 0;
for (const itemPath of paths) {
const trashPath = sanitizeTrashRel(itemPath);
const target = trashPathToFull(storage, trashPath);
const stat = await fsp.stat(target).catch(() => null);
if (!stat) continue;
if (stat.isDirectory()) await fsp.rm(target, { recursive: true, force: true });
else await fsp.unlink(target);
delete manifest.items[trashPath];
count++;
}
await writeTrashManifest(storage, manifest);
sendJson(res, 200, { ok: true, count });
}
async function createFolder(req, res) {
const body = await readJson(req);
const storage = getStorage(body.storage);
const name = sanitizeName(body.name || "");
if (!name) return sendJson(res, 400, { error: "Nombre invalido" });
const target = await availablePath(resolveInside(resolveInside(storage.root, sanitizeRel(body.path || "")), name));
await fsp.mkdir(target, { recursive: false });
sendJson(res, 200, { ok: true, name: path.basename(target) });
}
async function createTextFile(req, res) {
const body = await readJson(req);
const storage = getStorage(body.storage);
const name = ensureTxt(sanitizeName(body.name || ""));
if (!name) return sendJson(res, 400, { error: "Nombre invalido" });
const target = await availablePath(resolveInside(resolveInside(storage.root, sanitizeRel(body.path || "")), name));
await fsp.writeFile(target, body.content || "", { flag: "wx" });
sendJson(res, 200, { ok: true, name: path.basename(target) });
}
async function renameItem(req, res) {
const body = await readJson(req);
const storage = getStorage(body.storage);
const source = resolveInside(storage.root, sanitizeRel(body.path || ""));
const name = sanitizeName(body.name || "");
if (!name) return sendJson(res, 400, { error: "Nombre invalido" });
let target = resolveInside(path.dirname(source), name);
if (target !== source) target = await availablePath(target);
await fsp.rename(source, target);
sendJson(res, 200, { ok: true, name: path.basename(target) });
}
async function copyItem(req, res) {
const body = await readJson(req);
const sourceStorage = getStorage(body.sourceStorage);
const targetStorage = getStorage(body.targetStorage);
if (Array.isArray(body.sourcePaths)) {
const targetDir = resolveInside(targetStorage.root, sanitizeRel(body.targetPath || ""));
for (const sourcePath of body.sourcePaths) {
const source = resolveInside(sourceStorage.root, sanitizeRel(sourcePath || ""));
const target = await availablePath(resolveInside(targetDir, path.basename(source)));
ensureNotInsideSelf(source, target);
await copyRecursive(source, target);
}
return sendJson(res, 200, { ok: true, count: body.sourcePaths.length });
}
const source = resolveInside(sourceStorage.root, sanitizeRel(body.sourcePath || ""));
const target = await availablePath(resolveInside(resolveInside(targetStorage.root, sanitizeRel(body.targetPath || "")), path.basename(source)));
ensureNotInsideSelf(source, target);
await copyRecursive(source, target);
sendJson(res, 200, { ok: true });
}
async function moveItem(req, res) {
const body = await readJson(req);
const sourceStorage = getStorage(body.sourceStorage);
const targetStorage = getStorage(body.targetStorage);
const source = resolveInside(sourceStorage.root, sanitizeRel(body.sourcePath || ""));
const target = await availablePath(resolveInside(resolveInside(targetStorage.root, sanitizeRel(body.targetPath || "")), path.basename(source)));
ensureNotInsideSelf(source, target);
await fsp.rename(source, target).catch(async (error) => {
if (error.code !== "EXDEV") throw error;
await copyRecursive(source, target);
await fsp.rm(source, { recursive: true, force: true });
});
sendJson(res, 200, { ok: true });
}
async function smbLogin(req, res, body, ip) {
const user = String(body.user || "").trim();
const password = String(body.password || "");
if (!user || !password) {
recordLoginFailure(ip);
return sendJson(res, 401, { error: "Usuario o contrasena incorrectos" });
}
const auth = { user, password };
await smbListShares(auth);
loginAttempts.delete(ip);
const id = crypto.randomBytes(32).toString("hex");
sessions.set(id, { user, auth, createdAt: Date.now(), expiresAt: Date.now() + SESSION_TTL_MS });
setCookie(res, "vault_session", id, `Max-Age=${Math.floor(SESSION_TTL_MS / 1000)}; HttpOnly; SameSite=Lax`);
sendJson(res, 200, { ok: true });
}
async function smbListStorages(res, session) {
const shares = await smbListShares(session.auth);
sendJson(res, 200, {
nasName: NAS_NAME,
storages: shares.map((share) => ({ id: slugify(share), name: share, share, count: 0 }))
});
}
async function smbStorageStatus(res, session) {
const shares = await smbListShares(session.auth).catch(() => []);
sendJson(res, 200, {
nasName: NAS_NAME,
storages: shares.map((share) => ({
id: slugify(share),
name: share,
root: `//${SMB_HOST}/${share}`,
exists: true,
writable: true,
readonly: false
}))
});
}
async function smbListFiles(res, url, session) {
const storage = await smbStorageFromUrl(url, session.auth);
const relative = sanitizeRel(url.searchParams.get("path") || "");
const result = await smbLs(session.auth, storage.share, relative);
sendJson(res, 200, {
nasName: NAS_NAME,
storage: { id: storage.id, name: storage.name },
path: relative,
parent: parentRel(relative),
items: sortItems(result.items.map((item) => ({
...item,
path: joinRel(relative, item.name),
storage: storage.id
})), "name")
});
}
async function smbUploadFile(req, res, url, session) {
const storage = await smbStorageFromUrl(url, session.auth);
const folder = sanitizeRel(url.searchParams.get("path") || "");
const rawName = url.searchParams.get("name") || req.headers["x-file-name"] || "archivo";
const fileName = sanitizeName(String(rawName));
if (!fileName) return sendJson(res, 400, { error: "Nombre invalido" });
const tmp = await tmpPath(fileName);
try {
await pipeline(req, fs.createWriteStream(tmp, { flags: "w" }));
await smbCommand(session.auth, storage.share, [
...smbCdCommands(folder),
`put ${smbQuote(tmp)} ${smbQuote(fileName)}`
]);
sendJson(res, 200, { ok: true, name: fileName });
} finally {
await cleanupTmp(tmp);
}
}
async function smbDownloadFile(req, res, url, session) {
const { storage, relative, fileName } = await smbFileTarget(url, session.auth);
const tmp = await smbDownloadToTemp(session.auth, storage.share, relative, fileName);
const stat = await fsp.stat(tmp);
const cleanup = () => cleanupTmp(tmp);
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Length": stat.size,
"Content-Disposition": `attachment; filename="${encodeURIComponent(fileName)}"`
});
fs.createReadStream(tmp).pipe(res);
res.on("finish", cleanup);
res.on("close", cleanup);
}
async function smbPreviewFile(req, res, url, session) {
const { storage, relative, fileName } = await smbFileTarget(url, session.auth);
const ext = path.extname(fileName).toLowerCase();
const types = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".gif": "image/gif",
".mp4": "video/mp4",
".m4v": "video/mp4",
".webm": "video/webm",
".mov": "video/quicktime"
};
if (!types[ext]) return sendJson(res, 415, { error: "Sin vista previa" });
const tmp = await smbDownloadToTemp(session.auth, storage.share, relative, fileName);
const stat = await fsp.stat(tmp);
const cleanup = () => cleanupTmp(tmp);
res.on("finish", cleanup);
res.on("close", cleanup);
if (req.headers.range) return streamRange(res, tmp, stat.size, types[ext], req.headers.range);
res.writeHead(200, {
"Accept-Ranges": "bytes",
"Content-Type": types[ext],
"Content-Length": stat.size,
"Cache-Control": "private, max-age=60"
});
fs.createReadStream(tmp).pipe(res);
}
async function smbDetailsFile(res, url, session) {
const storage = await smbStorageFromUrl(url, session.auth);
const relative = sanitizeRel(url.searchParams.get("path") || "");
const folder = parentRel(relative);
const name = path.posix.basename(relative);
const result = await smbLs(session.auth, storage.share, folder);
const item = result.items.find((entry) => entry.name === name);
if (!item) return sendJson(res, 404, { error: "No encontrado" });
sendJson(res, 200, {
item: {
name,
path: relative,
storage: { id: storage.id, name: storage.name },
type: item.type,
kind: item.kind,
size: item.size,
modified: item.modified,
created: item.modified,
readonly: false
}
});
}
async function smbGetTextFile(res, url, session) {
const { storage, relative, fileName } = await smbFileTarget(url, session.auth);
const tmp = await smbDownloadToTemp(session.auth, storage.share, relative, fileName);
try {
const stat = await fsp.stat(tmp);
if (stat.size > TEXT_LIMIT_BYTES) return sendJson(res, 413, { error: "Archivo demasiado grande para editar" });
sendJson(res, 200, { content: await fsp.readFile(tmp, "utf8") });
} finally {
await cleanupTmp(tmp);
}
}
async function smbPutTextFile(req, res, url, session) {
const { storage, relative, folder, fileName } = await smbFileTarget(url, session.auth);
const body = await readJson(req, TEXT_LIMIT_BYTES + 4096);
const tmp = await tmpPath(fileName);
try {
await fsp.writeFile(tmp, String(body.content || ""), "utf8");
await smbCommand(session.auth, storage.share, [
...smbCdCommands(folder),
`put ${smbQuote(tmp)} ${smbQuote(fileName)}`
]);
sendJson(res, 200, { ok: true });
} finally {
await cleanupTmp(tmp);
}
}
async function smbCreateFolder(req, res, session) {
const body = await readJson(req);
const storage = await smbStorageFromId(body.storage, session.auth);
const folder = sanitizeRel(body.path || "");
const name = sanitizeName(body.name || "");
if (!name) return sendJson(res, 400, { error: "Nombre invalido" });
await smbCommand(session.auth, storage.share, [
...smbCdCommands(folder),
`mkdir ${smbQuote(name)}`
]);
sendJson(res, 200, { ok: true, name });
}
async function smbCreateTextFile(req, res, session) {
const body = await readJson(req);
const storage = await smbStorageFromId(body.storage, session.auth);
const folder = sanitizeRel(body.path || "");
const name = ensureTxt(sanitizeName(body.name || ""));
if (!name) return sendJson(res, 400, { error: "Nombre invalido" });
const tmp = await tmpPath(name);
try {
await fsp.writeFile(tmp, body.content || "", "utf8");
await smbCommand(session.auth, storage.share, [
...smbCdCommands(folder),
`put ${smbQuote(tmp)} ${smbQuote(name)}`
]);
sendJson(res, 200, { ok: true, name });
} finally {
await cleanupTmp(tmp);
}
}
async function smbRenameItem(req, res, session) {
const body = await readJson(req);
const storage = await smbStorageFromId(body.storage, session.auth);
const relative = sanitizeRel(body.path || "");
const folder = parentRel(relative);
const oldName = path.posix.basename(relative);
const newName = sanitizeName(body.name || "");
if (!relative || !newName) return sendJson(res, 400, { error: "Nombre invalido" });
await smbCommand(session.auth, storage.share, [
...smbCdCommands(folder),
`rename ${smbQuote(oldName)} ${smbQuote(newName)}`
]);
sendJson(res, 200, { ok: true, name: newName });
}
async function smbTrashFile(req, res, session) {
const body = await readJson(req);
const storage = await smbStorageFromId(body.storage, session.auth);
const relative = sanitizeRel(body.path || "");
await smbDeletePath(session.auth, storage.share, relative);
sendJson(res, 200, { ok: true, trashed: { path: relative, originalPath: relative } });
}
async function smbTrashMany(req, res, session) {
const body = await readJson(req);
const storage = await smbStorageFromId(body.storage, session.auth);
const paths = Array.isArray(body.paths) ? body.paths : [];
let count = 0;
for (const itemPath of paths) {
await smbDeletePath(session.auth, storage.share, sanitizeRel(itemPath)).then(() => count++).catch(() => {});
}
sendJson(res, 200, { ok: true, count, trashed: [] });
}
async function smbTrashFileUrl(res, url, session) {
const storage = await smbStorageFromUrl(url, session.auth);
const relative = sanitizeRel(url.searchParams.get("path") || "");
await smbDeletePath(session.auth, storage.share, relative);
sendJson(res, 200, { ok: true, trashed: { path: relative, originalPath: relative } });
}
async function smbListTrash(res, url) {
const storage = { id: url.searchParams.get("storage") || "", name: url.searchParams.get("storage") || "" };
sendJson(res, 200, { storage, items: [] });
}
async function smbDeletePath(auth, share, relative) {
if (!relative) throw publicError(400, "Ruta invalida");
const folder = parentRel(relative);
const name = path.posix.basename(relative);
const info = await smbLs(auth, share, folder).catch(() => ({ items: [] }));
const item = info.items.find((entry) => entry.name === name);
const command = item?.type === "folder" ? "rmdir" : "del";
await smbCommand(auth, share, [
...smbCdCommands(folder),
`${command} ${smbQuote(name)}`
]);
}
async function smbFileTarget(url, auth) {
const storage = await smbStorageFromUrl(url, auth);
const relative = sanitizeRel(url.searchParams.get("path") || "");
if (!relative) throw publicError(400, "Ruta invalida");
const folder = parentRel(relative);
const fileName = path.posix.basename(relative);
return { storage, relative, folder, fileName };
}
async function smbDownloadToTemp(auth, share, relative, fileName) {
const folder = parentRel(relative);
const tmp = await tmpPath(fileName);
await smbCommand(auth, share, [
...smbCdCommands(folder),
`get ${smbQuote(fileName)} ${smbQuote(tmp)}`
]);
return tmp;
}
async function smbListShares(auth) {
const result = await runSmbClient(auth, ["-g", "-L", `//${SMB_HOST}`]);
const shares = [];
for (const line of result.stdout.split(/\r?\n/)) {
const parts = line.split("|");
if (parts[0] !== "Disk" || !parts[1]) continue;
if (parts[1].endsWith("$")) continue;
shares.push(parts[1]);
}
return [...new Set(shares)];
}
async function smbLs(auth, share, relative) {
const stdout = await smbCommand(auth, share, [...smbCdCommands(relative), "ls"]);
return { items: parseSmbLs(stdout) };
}
function parseSmbLs(output) {
const items = [];
for (const line of output.split(/\r?\n/)) {
const match = /^\s*(.+?)\s+([A-Z]+)\s+(\d+)\s+(.+)$/.exec(line);
if (!match) continue;
const name = match[1].trim();
if (!name || name === "." || name === ".." || name.startsWith(".")) continue;
const flags = match[2];
const folder = flags.includes("D");
const modified = new Date(match[4].trim());
items.push({
name,
type: folder ? "folder" : "file",
kind: classifyName(name, folder),
size: Number(match[3]) || 0,
modified: Number.isNaN(modified.getTime()) ? new Date().toISOString() : modified.toISOString()
});
}
return items;
}
async function smbStorageFromUrl(url, auth) {
return smbStorageFromId(url.searchParams.get("storage"), auth);
}
async function smbStorageFromId(id, auth) {
const shares = await smbListShares(auth);
const share = shares.find((name) => slugify(name) === id) || shares[0];
if (!share) throw publicError(403, "No hay recursos SMB disponibles para este usuario");
return { id: slugify(share), name: share, share };
}
async function smbCommand(auth, share, commands) {
const result = await runSmbClient(auth, [`//${SMB_HOST}/${share}`, "-c", commands.join("; ")]);
return result.stdout;
}
async function runSmbClient(auth, args) {
const authFile = await smbAuthFile(auth);
return new Promise((resolve, reject) => {
const fullArgs = ["-m", "SMB3", "-A", authFile, ...args];
const child = spawn(SMBCLIENT_BIN, fullArgs, {
env: process.env,
stdio: ["ignore", "pipe", "pipe"]
});
let stdout = "";
let stderr = "";
let settled = false;
const finish = (handler) => {
if (settled) return;
settled = true;
clearTimeout(timer);
cleanupTmp(authFile).finally(handler);
};
const timer = setTimeout(() => child.kill("SIGTERM"), SMB_TIMEOUT_MS);
child.stdout.on("data", (chunk) => { stdout += chunk; });
child.stderr.on("data", (chunk) => { stderr += chunk; });
child.on("error", (error) => {
finish(() => {
if (error.code === "ENOENT") reject(publicError(500, `smbclient no esta instalado o no se encontro en ${SMBCLIENT_BIN}`));
else reject(error);
});
});
child.on("close", (code) => {
finish(() => {
if (code === 0) return resolve({ stdout, stderr });
reject(publicError(smbStatusCode(stderr || stdout), smbPublicError(stderr || stdout)));
});
});
});
}
async function smbAuthFile(auth) {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), "haze-smb-auth-"));
const file = path.join(dir, "credentials");
const lines = [
`username = ${auth.user}`,
`password = ${auth.password}`
];
if (SMB_WORKGROUP) lines.push(`workgroup = ${SMB_WORKGROUP}`);
await fsp.writeFile(file, `${lines.join("\n")}\n`, { mode: 0o600 });
return file;
}
function smbStatusCode(message) {
return /NT_STATUS_ACCESS_DENIED|NT_STATUS_LOGON_FAILURE|tree connect failed/i.test(message) ? 403 : 502;
}
function smbPublicError(message) {
if (/NT_STATUS_LOGON_FAILURE/i.test(message)) return "Usuario o contrasena incorrectos";
if (/NT_STATUS_ACCESS_DENIED/i.test(message)) return "No tienes permiso para esta carpeta";
if (/NT_STATUS_BAD_NETWORK_NAME|tree connect failed/i.test(message)) return "Recurso SMB no disponible";
return "Error SMB";
}
function smbCdCommands(relative) {
const clean = sanitizeRel(relative || "");
return clean ? [`cd ${smbQuote(clean)}`] : [];
}
function smbQuote(value) {
return `"${String(value).replace(/"/g, '\\"')}"`;
}
async function tmpPath(name) {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), "haze-smb-"));
return path.join(dir, sanitizeName(path.basename(name)) || "archivo");
}
async function cleanupTmp(filePath) {
await fsp.rm(path.dirname(filePath), { recursive: true, force: true }).catch(() => {});
}
function resolveRequestPath(url) {
const storage = getStorage(url.searchParams.get("storage"));
const relative = sanitizeRel(url.searchParams.get("path") || "");
return { storage, rel: { relative, fullPath: resolveInside(storage.root, relative) } };
}
function parseStorages(value) {
return value.split(",").map((entry, index) => {
const separator = entry.indexOf(":");
const name = separator === -1 ? `Almacenamiento ${index + 1}` : entry.slice(0, separator).trim();
const root = separator === -1 ? entry.trim() : entry.slice(separator + 1).trim();
const id = slugify(name || `storage-${index + 1}`);
return { id, name: name || id, root: path.resolve(root || "./data") };
}).filter((storage) => storage.root);
}
function getStorage(id) {
const storage = STORAGES.find((item) => item.id === id) || STORAGES[0];
if (!storage) throw publicError(400, "No hay almacenamientos configurados");
return storage;
}
async function fileInfo(storage, base, name, fullPath, dirent) {
const stat = await fsp.stat(fullPath);
const relPath = joinRel(base, name);
return {
name,
path: relPath,
type: dirent.isDirectory() ? "folder" : "file",
kind: classifyName(name, dirent.isDirectory()),
size: stat.size,
modified: stat.mtime.toISOString(),
storage: storage.id
};
}
async function detailInfo(storage, relative, fullPath) {
const stat = await fsp.stat(fullPath);
const name = path.basename(fullPath);
return {
name,
path: relative,
storage: { id: storage.id, name: storage.name },
type: stat.isDirectory() ? "folder" : "file",
kind: classifyName(name, stat.isDirectory()),
size: stat.size,
modified: stat.mtime.toISOString(),
created: stat.birthtime.toISOString(),
readonly: !await canWrite(fullPath)
};
}
function sortItems(items, key) {
return items.sort((a, b) => {
if (a.type !== b.type) return a.type === "folder" ? -1 : 1;
if (key === "date") return new Date(b.modified) - new Date(a.modified);
if (key === "size") return b.size - a.size;
if (key === "type") return a.kind.localeCompare(b.kind, "es", { sensitivity: "base" });
return a.name.localeCompare(b.name, "es", { sensitivity: "base" });
});
}
function classifyName(name, folder) {
if (folder) return "folder";
if (isImage(name)) return "image";
if (isVideo(name)) return "video";
if (isText(name)) return "text";
if (isDocument(name)) return "document";
return "file";
}
async function moveToTrash(storage, rawPath) {
await ensureTrash(storage);
const relative = sanitizeRel(rawPath);
if (!relative) throw publicError(400, "Ruta invalida");
const source = resolveInside(storage.root, relative);
const stat = await fsp.stat(source);
const today = new Date().toISOString().slice(0, 10);
const trashDayDir = path.join(trashRoot(storage), today);
await fsp.mkdir(trashDayDir, { recursive: true });
const target = await availablePath(path.join(trashDayDir, path.basename(source)));
await fsp.rename(source, target).catch(async (error) => {
if (error.code !== "EXDEV") throw error;
if (stat.isDirectory()) await copyRecursive(source, target);
else await fsp.copyFile(source, target, fs.constants.COPYFILE_EXCL);
await fsp.rm(source, { recursive: true, force: true });
});
const trashPath = path.relative(trashRoot(storage), target).split(path.sep).join("/");
const manifest = await readTrashManifest(storage);
manifest.items[trashPath] = {
originalPath: relative,
deletedAt: new Date().toISOString(),
name: path.basename(source),
type: stat.isDirectory() ? "folder" : "file"
};
await writeTrashManifest(storage, manifest);
return { path: trashPath, originalPath: relative };
}
async function ensureTrash(storage) {
await fsp.mkdir(trashRoot(storage), { recursive: true });
const manifestPath = path.join(trashRoot(storage), TRASH_MANIFEST);
if (!await exists(manifestPath)) await writeTrashManifest(storage, { version: 1, items: {} });
}
function trashRoot(storage) {
return path.join(storage.root, TRASH_DIR);
}
function trashPathToFull(storage, relative) {
return resolveInside(trashRoot(storage), sanitizeTrashRel(relative));
}
function sanitizeTrashRel(input) {
return String(input).split("/").map((part) => sanitizeName(part)).filter(Boolean).join("/");
}
async function readTrashManifest(storage) {
await ensureTrash(storage);
const manifestPath = path.join(trashRoot(storage), TRASH_MANIFEST);
try {
const parsed = JSON.parse(await fsp.readFile(manifestPath, "utf8"));
if (!parsed.items) parsed.items = {};
return parsed;
} catch {
return { version: 1, items: {} };
}
}
async function writeTrashManifest(storage, manifest) {