File size: 4,387 Bytes
c399c92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""云端相机 - 存储与用户管理

目录结构(默认根目录 /data,Hugging Face Space 持久化磁盘):
  /data/
    .secret              # 签名密钥(首次启动自动生成,持久保存)
    .users/<name>.json   # 用户 PIN 哈希
    <name>/index.json    # 相册索引(照片元数据列表)
    <name>/<id>.jpg      # 原图
    <name>/<id>_thumb.jpg# 缩略图
"""
import hashlib
import hmac
import json
import os
import re
import time
import uuid
from pathlib import Path

DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
USERS_DIR = DATA_DIR / ".users"

USERNAME_RE = re.compile(r"^[\w\u4e00-\u9fff-]{1,24}$")
PIN_RE = re.compile(r"^.{4,20}$")


def ensure_dirs() -> None:
    USERS_DIR.mkdir(parents=True, exist_ok=True)


def _user_file(username: str) -> Path:
    return USERS_DIR / f"{username}.json"


def _user_dir(username: str) -> Path:
    return DATA_DIR / username


def _index_file(username: str) -> Path:
    return _user_dir(username) / "index.json"


def valid_username(username: str) -> bool:
    return bool(username) and bool(USERNAME_RE.match(username))


def valid_pin(pin: str) -> bool:
    return bool(pin) and bool(PIN_RE.match(pin))


def _hash_pin(pin: str, salt: str) -> str:
    return hashlib.sha256(f"{salt}:{pin}".encode("utf-8")).hexdigest()


def user_exists(username: str) -> bool:
    return _user_file(username).exists()


def create_user(username: str, pin: str) -> None:
    salt = uuid.uuid4().hex
    _user_file(username).write_text(
        json.dumps({"salt": salt, "pin_hash": _hash_pin(pin, salt)}),
        encoding="utf-8",
    )
    _user_dir(username).mkdir(parents=True, exist_ok=True)
    _index_file(username).write_text(json.dumps({"photos": []}), encoding="utf-8")


def verify_user(username: str, pin: str) -> bool:
    f = _user_file(username)
    if not f.exists():
        return False
    try:
        data = json.loads(f.read_text(encoding="utf-8"))
    except Exception:
        return False
    return _hash_pin(pin, data.get("salt", "")) == data.get("pin_hash", "")


def list_photos(username: str) -> list:
    f = _index_file(username)
    if not f.exists():
        return []
    try:
        return json.loads(f.read_text(encoding="utf-8")).get("photos", [])
    except Exception:
        return []


def add_photo(username: str, photo: dict) -> None:
    f = _index_file(username)
    data = {"photos": []}
    if f.exists():
        try:
            data = json.loads(f.read_text(encoding="utf-8"))
        except Exception:
            data = {"photos": []}
    data.setdefault("photos", []).insert(0, photo)
    f.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")


def remove_photo(username: str, photo_id: str) -> bool:
    f = _index_file(username)
    if not f.exists():
        return False
    try:
        data = json.loads(f.read_text(encoding="utf-8"))
    except Exception:
        return False
    before = len(data.get("photos", []))
    data["photos"] = [p for p in data.get("photos", []) if p["id"] != photo_id]
    f.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
    return len(data["photos"]) < before


# ---------- 图片访问签名 ----------

def get_secret() -> bytes:
    """签名密钥:优先环境变量 SIGN_SECRET,否则用持久化的随机密钥。"""
    env = os.environ.get("SIGN_SECRET")
    if env:
        return env.encode("utf-8")
    f = DATA_DIR / ".secret"
    if f.exists():
        return f.read_text(encoding="utf-8").strip().encode("utf-8")
    s = uuid.uuid4().hex
    f.write_text(s, encoding="utf-8")
    return s.encode("utf-8")


def make_token(username: str, photo_id: str, ttl: int = 86400) -> str:
    """为图片生成带过期时间的访问令牌。"""
    expires = int(time.time()) + ttl
    msg = f"{username}/{photo_id}/{expires}".encode("utf-8")
    sig = hmac.new(get_secret(), msg, hashlib.sha256).hexdigest()
    return f"{expires}.{sig}"


def verify_token(username: str, photo_id: str, token: str) -> bool:
    try:
        expires_str, sig = token.split(".", 1)
        expires = int(expires_str)
    except Exception:
        return False
    if time.time() > expires:
        return False
    msg = f"{username}/{photo_id}/{expires}".encode("utf-8")
    expect = hmac.new(get_secret(), msg, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expect, sig)