-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1212 lines (1020 loc) · 41.3 KB
/
app.py
File metadata and controls
1212 lines (1020 loc) · 41.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
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
import asyncio
import os
import re
import stat
import time
from contextlib import asynccontextmanager
from functools import partial
import databases
import sqlalchemy
from fastapi import FastAPI, HTTPException, UploadFile, File, Query, Form, Request, Depends
from fastapi.responses import StreamingResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel
from typing import Optional
from starlette.middleware.base import BaseHTTPMiddleware
from models import metadata, nodes
from ssh_manager import pool, op_log, SSHConnection, local_conn
from security import (
encrypt_field, decrypt_field, verify_password,
rate_limiter, ADMIN_USER, ADMIN_PWD_HASH,
)
import logging as _logging
_log = _logging.getLogger("ssh-fm")
DATABASE_URL = "sqlite:///data/nodes.db"
def _safe_err(e: Exception) -> str:
"""Strip internal paths from error messages before returning to client."""
msg = str(e)
msg = re.sub(r"(/[^\s'\"]+/\.ssh/[^\s'\"]*)", "[key-path]", msg)
msg = re.sub(r"(/home/[^\s'\"]+|/root/[^\s'\"]+|/tmp/[^\s'\"]+)", "[server-path]", msg)
if len(msg) > 200:
msg = msg[:200] + "…"
return msg
database = databases.Database(DATABASE_URL)
SENSITIVE_FIELDS = {"password", "private_key"}
# ---------- Security middleware ----------
class SecurityMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Cache-Control"] = "no-store"
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; "
"font-src 'self' https://cdnjs.cloudflare.com; "
"script-src 'self' 'unsafe-inline'; "
"img-src 'self' data: blob:; "
"media-src 'self' blob:; "
"frame-src 'self' blob:; "
"connect-src 'self'"
)
return response
class AuthMiddleware(BaseHTTPMiddleware):
OPEN_PATHS = {"/api/login"}
async def dispatch(self, request: Request, call_next):
path = request.url.path
if path in self.OPEN_PATHS or path.startswith("/static/"):
return await call_next(request)
token = request.cookies.get("sfm_token")
if not token or not _verify_token(token):
if path.startswith("/api/"):
return JSONResponse({"detail": "Unauthorized"}, status_code=401)
return FileResponse("static/login.html")
return await call_next(request)
import secrets as _secrets
_active_tokens: set[str] = set()
def _make_token(username: str) -> str:
import hashlib, hmac as _hmac
from security import SECRET_KEY
nonce = _secrets.token_hex(8)
ts = str(int(time.time()))
msg = f"{username}:{ts}:{nonce}".encode()
sig = _hmac.new(SECRET_KEY, msg, hashlib.sha256).hexdigest()[:32]
token = f"{username}:{ts}:{nonce}:{sig}"
_active_tokens.add(token)
return token
def _verify_token(token: str) -> bool:
import hashlib, hmac as _hmac
from security import SECRET_KEY
if token not in _active_tokens:
return False
parts = token.split(":")
if len(parts) != 4:
return False
username, ts_str, nonce, sig = parts
try:
ts = int(ts_str)
except ValueError:
return False
if time.time() - ts > 86400 * 7:
_active_tokens.discard(token)
return False
msg = f"{username}:{ts_str}:{nonce}".encode()
expected = _hmac.new(SECRET_KEY, msg, hashlib.sha256).hexdigest()[:32]
return _hmac.compare_digest(sig, expected)
def _revoke_token(token: str):
_active_tokens.discard(token)
# ---------- App ----------
@asynccontextmanager
async def lifespan(app: FastAPI):
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.create_all(engine)
await database.connect()
yield
await database.disconnect()
app = FastAPI(title="SSH File Manager", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
app.add_middleware(SecurityMiddleware)
app.add_middleware(AuthMiddleware)
# ---------- Auth endpoints ----------
class LoginRequest(BaseModel):
username: str
password: str
@app.post("/api/login")
async def login(body: LoginRequest, request: Request):
client_ip = request.client.host if request.client else "unknown"
if rate_limiter.is_limited(client_ip):
raise HTTPException(429, "Too many attempts, try again later")
rate_limiter.record(client_ip)
if body.username == ADMIN_USER and verify_password(body.password, ADMIN_PWD_HASH):
token = _make_token(body.username)
response = JSONResponse({"ok": True})
response.set_cookie(
"sfm_token", token,
httponly=True, samesite="strict", secure=False, max_age=86400 * 7,
)
return response
raise HTTPException(401, "Invalid credentials")
@app.post("/api/logout")
async def logout(request: Request):
token = request.cookies.get("sfm_token", "")
_revoke_token(token)
response = JSONResponse({"ok": True})
response.delete_cookie("sfm_token")
return response
# ---------- Pydantic Models ----------
class NodeCreate(BaseModel):
name: str
host: str
port: int = 22
username: str
auth_type: str = "password"
password: str = ""
private_key: str = ""
key_file: str = ""
country: str = ""
provider: str = ""
business: str = ""
expire_date: str = ""
cost: str = ""
class NodeUpdate(BaseModel):
name: Optional[str] = None
host: Optional[str] = None
port: Optional[int] = None
username: Optional[str] = None
auth_type: Optional[str] = None
password: Optional[str] = None
private_key: Optional[str] = None
key_file: Optional[str] = None
country: Optional[str] = None
provider: Optional[str] = None
business: Optional[str] = None
expire_date: Optional[str] = None
cost: Optional[str] = None
class FileAction(BaseModel):
path: str
dest: str = ""
class CompressAction(BaseModel):
paths: list[str]
archive_name: str
cwd: str
class DecompressAction(BaseModel):
path: str
cwd: str
class MkdirAction(BaseModel):
path: str
class RenameAction(BaseModel):
old_path: str
new_path: str
class TrashRestoreAction(BaseModel):
trash_path: str
original_path: str
class FileWriteAction(BaseModel):
path: str
content: str
class FileCreateAction(BaseModel):
path: str
content: str = ""
class TransferAction(BaseModel):
src_node_id: int
src_path: str
dst_node_id: int
dst_path: str
# ---------- Helpers ----------
def sanitize_filename(name: str) -> str:
return re.sub(r'[^\w\.\-\u4e00-\u9fff\u3000-\u303f]', '_', name)
def _validate_path(path: str) -> str:
"""Normalize and validate remote path to prevent path traversal."""
if not path:
raise HTTPException(400, "路径不能为空")
normed = os.path.normpath(path)
if not normed.startswith("/"):
raise HTTPException(400, "路径必须是绝对路径")
if "\x00" in path:
raise HTTPException(400, "路径包含非法字符")
return normed
MAX_UPLOAD_SIZE = 500 * 1024 * 1024 # 500 MB
MAX_TRANSFER_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB
_hw_cache: dict[int, dict] = {}
def mask_node(row: dict) -> dict:
"""Strip sensitive fields before sending to client."""
r = dict(row)
for f in SENSITIVE_FIELDS:
if f in r and r[f]:
r[f] = "••••••"
return r
# ---------- Node CRUD ----------
@app.get("/api/nodes")
async def list_nodes():
rows = await database.fetch_all(nodes.select())
result = []
for r in rows:
n = mask_node(dict(r._mapping))
n["hw"] = _hw_cache.get(n["id"])
result.append(n)
return result
@app.get("/api/nodes/{node_id}")
async def get_node(node_id: int):
row = await database.fetch_one(nodes.select().where(nodes.c.id == node_id))
if not row:
raise HTTPException(404, "Node not found")
r = dict(row._mapping)
has_pw = bool(r.get("password"))
has_pk = bool(r.get("private_key"))
r["password"] = "••••••" if has_pw else ""
r["private_key"] = "••••••" if has_pk else ""
return r
@app.post("/api/nodes")
async def create_node(node: NodeCreate):
data = node.model_dump()
data["password"] = encrypt_field(data["password"])
data["private_key"] = encrypt_field(data["private_key"])
query = nodes.insert().values(**data)
last_id = await database.execute(query)
return {"id": last_id, **mask_node(node.model_dump())}
@app.put("/api/nodes/{node_id}")
async def update_node(node_id: int, node: NodeUpdate):
values = {k: v for k, v in node.model_dump().items() if v is not None}
if not values:
raise HTTPException(400, "No fields to update")
if "password" in values and values["password"] != "••••••":
values["password"] = encrypt_field(values["password"])
elif "password" in values:
del values["password"]
if "private_key" in values and values["private_key"] != "••••••":
values["private_key"] = encrypt_field(values["private_key"])
elif "private_key" in values:
del values["private_key"]
if values:
query = nodes.update().where(nodes.c.id == node_id).values(**values)
await database.execute(query)
conn_fields = {"host", "port", "username", "auth_type", "password", "private_key", "key_file"}
if conn_fields & values.keys():
pool.remove(node_id)
return {"ok": True}
@app.delete("/api/nodes/{node_id}")
async def delete_node(node_id: int):
pool.remove(node_id)
query = nodes.delete().where(nodes.c.id == node_id)
await database.execute(query)
return {"ok": True}
# ---------- SSH connect helper ----------
async def get_conn(node_id: int):
if node_id == 0:
return local_conn
row = await database.fetch_one(nodes.select().where(nodes.c.id == node_id))
if not row:
raise HTTPException(404, "Node not found")
r = dict(row._mapping)
try:
return pool.get(
node_id,
host=r["host"], port=r["port"], username=r["username"],
password=decrypt_field(r.get("password", "")),
private_key=decrypt_field(r.get("private_key", "")),
auth_type=r["auth_type"],
)
except Exception as e:
_log.warning("SSH connect failed node=%s: %s", node_id, e)
raise HTTPException(502, f"SSH connection failed: {_safe_err(e)}")
async def run_sync(fn, *args, **kwargs):
"""Run blocking function in thread pool to avoid blocking the event loop."""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, partial(fn, *args, **kwargs))
@app.post("/api/connect/{node_id}")
async def test_connect(node_id: int):
conn = await get_conn(node_id)
if node_id == 0:
return {"status": "connected", "echo": "ok"}
try:
out, _ = await run_sync(conn.exec_command, "echo ok")
except Exception:
pool.remove(node_id)
conn = await get_conn(node_id)
out, _ = await run_sync(conn.exec_command, "echo ok")
asyncio.ensure_future(_cache_hw_info(node_id, conn))
return {"status": "connected", "echo": out.strip()}
async def _cache_hw_info(node_id: int, conn):
try:
combined, _ = await run_sync(conn.exec_command,
"nproc 2>/dev/null || grep -c ^processor /proc/cpuinfo 2>/dev/null || echo 0; "
"echo '___'; "
"free -b 2>/dev/null | awk 'NR==2{print $2}'; "
"echo '___'; "
"df -B1 / 2>/dev/null | awk 'NR==2{print $2}'"
)
parts = combined.split("___\n")
cpu = int(parts[0].strip().split("\n")[0]) if parts[0].strip() else 0
mem = int(parts[1].strip()) if len(parts) > 1 and parts[1].strip().isdigit() else 0
disk = int(parts[2].strip()) if len(parts) > 2 and parts[2].strip().isdigit() else 0
_hw_cache[node_id] = {"cpu": cpu, "mem_total": mem, "disk_total": disk}
except Exception:
pass
# ---------- File operations ----------
@app.get("/api/files/{node_id}")
async def list_files(node_id: int, path: str = "/"):
path = _validate_path(path)
conn = await get_conn(node_id)
try:
entries = await run_sync(conn.list_dir, path)
return {"path": path, "entries": entries}
except FileNotFoundError:
raise HTTPException(404, "Path not found")
except PermissionError:
raise HTTPException(403, "Permission denied")
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.get("/api/files/{node_id}/download")
async def download_file(node_id: int, path: str = Query(...)):
path = _validate_path(path)
conn = await get_conn(node_id)
try:
st = await run_sync(conn.get_stat, path)
if stat.S_ISDIR(st.st_mode):
raise HTTPException(400, "Cannot download a directory directly, compress it first")
data = await run_sync(conn.read_file, path)
filename = sanitize_filename(os.path.basename(path))
return StreamingResponse(
iter([data]),
media_type="application/octet-stream",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, _safe_err(e))
MAX_PREVIEW_SIZE = 20 * 1024 * 1024 # 20MB
MIME_MAP = {
".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png",
".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml",
".bmp": "image/bmp", ".ico": "image/x-icon",
".mp4": "video/mp4", ".webm": "video/webm",
".mp3": "audio/mpeg", ".wav": "audio/wav", ".ogg": "audio/ogg",
".pdf": "application/pdf",
}
@app.get("/api/files/{node_id}/preview")
async def preview_file(node_id: int, path: str = Query(...)):
path = _validate_path(path)
conn = await get_conn(node_id)
try:
st = await run_sync(conn.get_stat, path)
if stat.S_ISDIR(st.st_mode):
raise HTTPException(400, "Cannot preview a directory")
if st.st_size > MAX_PREVIEW_SIZE:
raise HTTPException(413, "文件过大,无法预览")
ext = os.path.splitext(path)[1].lower()
mime = MIME_MAP.get(ext)
if not mime:
raise HTTPException(415, "不支持预览该文件类型")
data = await run_sync(conn.read_file, path)
return Response(content=data, media_type=mime)
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.post("/api/files/{node_id}/upload")
async def upload_file(node_id: int, path: str = Form(...), file: UploadFile = File(...)):
path = _validate_path(path)
safe_name = os.path.basename(file.filename or "upload")
if not safe_name or safe_name.startswith("."):
safe_name = "upload"
conn = await get_conn(node_id)
try:
content = await file.read()
if len(content) > MAX_UPLOAD_SIZE:
raise HTTPException(413, f"文件过大 ({len(content)} bytes, 上限 {MAX_UPLOAD_SIZE})")
remote_path = path.rstrip("/") + "/" + safe_name
await run_sync(conn.write_file, remote_path, content)
return {"ok": True, "path": remote_path}
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, _safe_err(e))
MAX_EDIT_SIZE = 2 * 1024 * 1024 # 2MB
@app.get("/api/files/{node_id}/content")
async def read_file_content(node_id: int, path: str = Query(...)):
path = _validate_path(path)
conn = await get_conn(node_id)
try:
st = await run_sync(conn.get_stat, path)
if stat.S_ISDIR(st.st_mode):
raise HTTPException(400, "Cannot read a directory")
if st.st_size > MAX_EDIT_SIZE:
raise HTTPException(413, f"File too large to edit ({st.st_size} bytes, max {MAX_EDIT_SIZE})")
data = await run_sync(conn.read_file, path)
try:
text = data.decode("utf-8")
except UnicodeDecodeError:
raise HTTPException(415, "File is not a text file (binary content)")
return {"path": path, "content": text, "size": st.st_size}
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.post("/api/files/{node_id}/content")
async def write_file_content(node_id: int, body: FileWriteAction):
path = _validate_path(body.path)
conn = await get_conn(node_id)
try:
await run_sync(conn.write_file, path, body.content.encode("utf-8"))
return {"ok": True, "path": path}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.post("/api/files/{node_id}/create")
async def create_file(node_id: int, body: FileCreateAction):
path = _validate_path(body.path)
conn = await get_conn(node_id)
try:
await run_sync(conn.write_file, path, body.content.encode("utf-8"))
return {"ok": True, "path": path}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.post("/api/files/{node_id}/mkdir")
async def mkdir(node_id: int, body: MkdirAction):
path = _validate_path(body.path)
conn = await get_conn(node_id)
try:
await run_sync(conn.mkdir, path)
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.post("/api/files/{node_id}/rename")
async def rename_file(node_id: int, body: RenameAction):
old_path = _validate_path(body.old_path)
new_path = _validate_path(body.new_path)
conn = await get_conn(node_id)
try:
await run_sync(conn.rename, old_path, new_path)
op_log.push(node_id, {
"type": "rename", "time": time.time(),
"old_path": old_path, "new_path": new_path,
})
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.post("/api/files/{node_id}/copy")
async def copy_file(node_id: int, body: FileAction):
src = _validate_path(body.path)
dest = _validate_path(body.dest)
conn = await get_conn(node_id)
try:
await run_sync(conn.copy_file, src, dest)
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.post("/api/files/{node_id}/move")
async def move_file(node_id: int, body: FileAction):
src = _validate_path(body.path)
dest = _validate_path(body.dest)
conn = await get_conn(node_id)
try:
await run_sync(conn.move_file, src, dest)
op_log.push(node_id, {
"type": "move", "time": time.time(),
"src": src, "dest": dest,
})
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.delete("/api/files/{node_id}")
async def delete_file(node_id: int, path: str = Query(...)):
path = _validate_path(path)
conn = await get_conn(node_id)
try:
trash_path = await run_sync(conn.trash, path)
op_log.push(node_id, {
"type": "delete", "time": time.time(),
"original_path": path, "trash_path": trash_path,
})
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.post("/api/files/{node_id}/compress")
async def compress_files(node_id: int, body: CompressAction):
cwd = _validate_path(body.cwd)
paths = [_validate_path(p) for p in body.paths]
archive = body.archive_name
if "/" in archive or "\\" in archive or ".." in archive:
raise HTTPException(400, "压缩文件名不合法")
conn = await get_conn(node_id)
try:
await run_sync(conn.compress, paths, archive, cwd)
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.post("/api/files/{node_id}/decompress")
async def decompress_file(node_id: int, body: DecompressAction):
path = _validate_path(body.path)
cwd = _validate_path(body.cwd)
conn = await get_conn(node_id)
try:
await run_sync(conn.decompress, path, cwd)
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
# ---------- Cross-server Transfer ----------
@app.post("/api/transfer")
async def transfer_file(body: TransferAction):
src_path = _validate_path(body.src_path)
dst_path = _validate_path(body.dst_path)
src_conn = await get_conn(body.src_node_id)
dst_conn = await get_conn(body.dst_node_id)
try:
st = await run_sync(src_conn.get_stat, src_path)
basename_name = os.path.basename(src_path)
if stat.S_ISDIR(st.st_mode):
tmp_name = f"/tmp/.sfm_xfer_{int(time.time()*1000)}.tar.gz"
parent = os.path.dirname(src_path)
q = SSHConnection._quote
_, err = await run_sync(
src_conn.exec_command,
f"cd {q(parent)} && tar czf {q(tmp_name)} {q(basename_name)}"
)
if err.strip() and "tar:" not in err:
raise RuntimeError(f"源压缩失败: {err.strip()}")
try:
data = await run_sync(src_conn.read_file, tmp_name)
_log.info("transfer dir %s (%d bytes tar) -> node %s:%s",
src_path, len(data), body.dst_node_id, dst_path)
if len(data) > MAX_TRANSFER_SIZE:
raise HTTPException(413, f"目录过大 ({len(data)} bytes), 超出传输限制")
await run_sync(dst_conn.write_file, tmp_name, data)
_, err2 = await run_sync(
dst_conn.exec_command,
f"cd {q(dst_path)} && tar xzf {q(tmp_name)}"
)
if err2.strip() and "tar:" not in err2:
_log.warning("transfer untar stderr: %s", err2.strip())
raise RuntimeError(f"目标解压失败: {err2.strip()}")
finally:
await run_sync(src_conn.exec_command, f"rm -f {q(tmp_name)}")
await run_sync(dst_conn.exec_command, f"rm -f {q(tmp_name)}")
return {"ok": True, "type": "directory", "name": basename_name}
else:
if st.st_size > MAX_TRANSFER_SIZE:
raise HTTPException(413, f"文件过大 ({st.st_size} bytes), 超出传输限制")
data = await run_sync(src_conn.read_file, src_path)
dst_full = dst_path.rstrip("/") + "/" + basename_name
_log.info("transfer file %s (%d bytes) -> node %s:%s",
src_path, len(data), body.dst_node_id, dst_full)
await run_sync(dst_conn.write_file, dst_full, data)
try:
dst_st = await run_sync(dst_conn.get_stat, dst_full)
_log.info("transfer verify: dst size=%d, src size=%d", dst_st.st_size, len(data))
except Exception as ve:
_log.warning("transfer verify failed: %s", ve)
return {"ok": True, "type": "file", "name": basename_name, "size": len(data)}
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, _safe_err(e))
# ---------- Undo ----------
@app.get("/api/undo/{node_id}")
async def get_undo_stack(node_id: int):
history = op_log.list(node_id)
last = op_log.peek(node_id)
return {"last": last, "history": history}
@app.post("/api/undo/{node_id}")
async def undo_last(node_id: int):
op = op_log.pop(node_id)
if not op:
raise HTTPException(404, "没有可撤销的操作")
conn = await get_conn(node_id)
try:
if op["type"] == "delete":
await run_sync(conn.restore_from_trash, op["trash_path"], op["original_path"])
return {"ok": True, "undone": "delete", "restored": op["original_path"]}
elif op["type"] == "move":
await run_sync(conn.move_file, op["dest"], op["src"])
return {"ok": True, "undone": "move", "restored": op["src"]}
elif op["type"] == "rename":
await run_sync(conn.rename, op["new_path"], op["old_path"])
return {"ok": True, "undone": "rename", "restored": op["old_path"]}
else:
raise HTTPException(400, f"Unknown operation type: {op['type']}")
except Exception as e:
op_log.push(node_id, op)
raise HTTPException(500, f"Undo failed: {_safe_err(e)}")
# ---------- Trash ----------
@app.get("/api/trash/{node_id}")
async def list_trash(node_id: int):
conn = await get_conn(node_id)
return await run_sync(conn.list_trash)
@app.post("/api/trash/{node_id}/restore")
async def restore_trash(node_id: int, body: TrashRestoreAction):
tp = _validate_path(body.trash_path)
op = _validate_path(body.original_path)
conn = await get_conn(node_id)
try:
await run_sync(conn.restore_from_trash, tp, op)
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.delete("/api/trash/{node_id}")
async def empty_trash(node_id: int):
conn = await get_conn(node_id)
try:
await run_sync(conn.empty_trash)
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
@app.delete("/api/trash/{node_id}/item")
async def delete_trash_item(node_id: int, path: str = Query(...)):
path = _validate_path(path)
conn = await get_conn(node_id)
try:
await run_sync(conn.delete_trash_item, path)
return {"ok": True}
except Exception as e:
raise HTTPException(500, _safe_err(e))
# ---------- Monitor ----------
import shutil as _shutil
import socket as _socket
async def _get_local_stats() -> dict:
cpu = os.cpu_count() or 0
loads: list[str] = []
mem_total = mem_used = 0
try:
with open("/proc/loadavg") as f:
loads = f.read().strip().split()[:3]
except Exception:
pass
try:
with open("/proc/meminfo") as f:
info = {}
for line in f:
p = line.split()
if len(p) >= 2:
info[p[0].rstrip(":")] = int(p[1]) * 1024
mem_total = info.get("MemTotal", 0)
mem_used = mem_total - info.get("MemAvailable", 0)
except Exception:
pass
try:
du = _shutil.disk_usage("/")
disk_total, disk_used = du.total, du.used
except Exception:
disk_total = disk_used = 0
uptime_str = ""
try:
with open("/proc/uptime") as f:
secs = int(float(f.read().split()[0]))
d, r = divmod(secs, 86400)
h = r // 3600
uptime_str = f"up {d}d {h}h"
except Exception:
pass
return {"cpu": cpu, "load": loads, "mem_total": mem_total, "mem_used": mem_used,
"disk_total": disk_total, "disk_used": disk_used, "uptime": uptime_str}
async def _fetch_node_stats(conn) -> dict:
combined, _ = await run_sync(conn.exec_command,
"nproc 2>/dev/null || echo 0; echo '___'; "
"cat /proc/loadavg 2>/dev/null; echo '___'; "
"free -b 2>/dev/null | awk 'NR==2{print $2,$3}'; echo '___'; "
"df -B1 / 2>/dev/null | awk 'NR==2{print $2,$3}'; echo '___'; "
"uptime -p 2>/dev/null || uptime 2>/dev/null"
)
s = combined.split("___\n")
cpu = int(s[0].strip().split("\n")[0]) if s[0].strip().split("\n")[0].isdigit() else 0
loads = s[1].strip().split()[:3] if len(s) > 1 else []
mp = s[2].strip().split() if len(s) > 2 else []
mem_total = int(mp[0]) if mp and mp[0].isdigit() else 0
mem_used = int(mp[1]) if len(mp) > 1 and mp[1].isdigit() else 0
dp = s[3].strip().split() if len(s) > 3 else []
disk_total = int(dp[0]) if dp and dp[0].isdigit() else 0
disk_used = int(dp[1]) if len(dp) > 1 and dp[1].isdigit() else 0
uptime = s[4].strip() if len(s) > 4 else ""
return {"cpu": cpu, "load": loads, "mem_total": mem_total, "mem_used": mem_used,
"disk_total": disk_total, "disk_used": disk_used, "uptime": uptime}
@app.get("/api/monitor")
async def get_monitor():
results = []
local = await _get_local_stats()
local["node_id"] = 0
lm = _read_local_meta()
local["name"] = lm.get("name", "本机")
local["country"] = lm.get("country", "")
local["provider"] = lm.get("provider", "")
local["expire_date"] = lm.get("expire_date", "")
local["cost"] = lm.get("cost", "")
results.append(local)
rows = await database.fetch_all(nodes.select())
node_info = {}
for r in rows:
d = dict(r._mapping)
node_info[d["id"]] = d
connected_ids = set()
for node_id, conn in list(pool._pool.items()):
connected_ids.add(node_id)
info = node_info.get(node_id, {})
try:
st = await _fetch_node_stats(conn)
st["node_id"] = node_id
st["name"] = info.get("name", f"Node {node_id}")
st["expire_date"] = info.get("expire_date", "")
st["cost"] = info.get("cost", "")
st["country"] = info.get("country", "")
st["provider"] = info.get("provider", "")
results.append(st)
except Exception:
results.append({"node_id": node_id, "name": info.get("name", ""),
"expire_date": info.get("expire_date", ""),
"cost": info.get("cost", ""), "error": True})
for nid, info in node_info.items():
if nid not in connected_ids:
results.append({
"node_id": nid, "name": info.get("name", ""),
"expire_date": info.get("expire_date", ""),
"cost": info.get("cost", ""),
"country": info.get("country", ""),
"provider": info.get("provider", ""),
"offline": True,
})
all_nodes = []
for d in node_info.values():
all_nodes.append({
"id": d["id"], "name": d["name"],
"expire_date": d.get("expire_date", ""),
"cost": d.get("cost", ""),
"country": d.get("country", ""),
"provider": d.get("provider", ""),
})
return {"stats": results, "nodes": all_nodes}
LOCAL_META_FILE = "data/local_meta.json"
import json as _json
def _read_local_meta() -> dict:
defaults = {"name": "本机", "country": "", "provider": "", "business": "",
"expire_date": "", "cost": ""}
try:
with open(LOCAL_META_FILE, "r") as f:
d = _json.load(f)
defaults.update(d)
except (FileNotFoundError, _json.JSONDecodeError):
pass
return defaults
def _write_local_meta(data: dict):
os.makedirs("data", exist_ok=True)
with open(LOCAL_META_FILE, "w") as f:
_json.dump(data, f, ensure_ascii=False, indent=2)
@app.get("/api/local/meta")
async def get_local_meta():
return _read_local_meta()
class LocalMetaUpdate(BaseModel):
name: Optional[str] = None
country: Optional[str] = None
provider: Optional[str] = None
business: Optional[str] = None
expire_date: Optional[str] = None
cost: Optional[str] = None
@app.put("/api/local/meta")
async def update_local_meta(body: LocalMetaUpdate):
meta = _read_local_meta()
for k, v in body.model_dump().items():
if v is not None:
meta[k] = v
_write_local_meta(meta)
return {"ok": True}
@app.get("/api/local/info")
async def get_local_info():
hostname = _socket.gethostname()
loop = asyncio.get_event_loop()
try:
r = await loop.run_in_executor(None, lambda: subprocess.run(
["curl", "-s", "--connect-timeout", "3", "ifconfig.me"],
capture_output=True, text=True, timeout=5))
exit_ip = r.stdout.strip() if r.returncode == 0 else ""
except Exception:
exit_ip = ""
cpu = os.cpu_count() or 0
mem_total = 0
try:
with open("/proc/meminfo") as f:
for line in f:
if line.startswith("MemTotal:"):
mem_total = int(line.split()[1]) * 1024
break
except Exception:
pass
try:
du = _shutil.disk_usage("/")
disk_total = du.total
except Exception:
disk_total = 0
return {"hostname": hostname, "exit_ip": exit_ip, "cpu": cpu,
"mem_total": mem_total, "disk_total": disk_total}
# ---------- Local SSH Info ----------
@app.get("/api/local-ssh")
async def get_local_ssh_info():
"""Scan local ~/.ssh/ to show key files, known_hosts, ssh config."""
ssh_dir = os.path.expanduser("~/.ssh")
result = {"keys": [], "known_hosts": [], "configs": []}
if not os.path.isdir(ssh_dir):
return result
for fname in sorted(os.listdir(ssh_dir)):
fpath = os.path.join(ssh_dir, fname)