2023-08-14 01:56:46 +08:00
|
|
|
|
# @Time : 2023/8/13 19:54
|
|
|
|
|
|
# @Author : Lan
|
|
|
|
|
|
# @File : utils.py
|
|
|
|
|
|
# @Software: PyCharm
|
2023-08-14 05:03:07 +08:00
|
|
|
|
import datetime
|
2023-08-24 14:04:00 +08:00
|
|
|
|
import hashlib
|
2026-07-21 14:49:30 +08:00
|
|
|
|
import hmac
|
2025-05-21 00:14:40 +08:00
|
|
|
|
import os
|
|
|
|
|
|
import re
|
2026-06-09 00:53:11 +08:00
|
|
|
|
import secrets
|
2023-08-14 01:56:46 +08:00
|
|
|
|
import string
|
2023-08-24 14:04:00 +08:00
|
|
|
|
import time
|
2025-12-18 23:08:40 +08:00
|
|
|
|
|
2025-02-09 20:25:23 +08:00
|
|
|
|
from core.settings import settings
|
2023-08-14 01:56:46 +08:00
|
|
|
|
|
2025-02-15 22:00:53 +08:00
|
|
|
|
|
2023-08-14 01:56:46 +08:00
|
|
|
|
async def get_random_num():
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取随机数
|
|
|
|
|
|
:return:
|
|
|
|
|
|
"""
|
2026-06-09 00:53:11 +08:00
|
|
|
|
return secrets.randbelow(90000) + 10000
|
2023-08-14 01:56:46 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
r_s = string.ascii_uppercase + string.digits
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-09-09 16:21:35 +08:00
|
|
|
|
def validate_background_url(value) -> str:
|
|
|
|
|
|
"""Validate the site background config before it reaches the theme template.
|
|
|
|
|
|
|
|
|
|
|
|
Themes inject this value into inline CSS ``url('...')`` where html escaping
|
|
|
|
|
|
cannot neutralize a single-quote breakout, so only well-formed http(s) URLs
|
|
|
|
|
|
(or an empty string) are accepted.
|
|
|
|
|
|
"""
|
|
|
|
|
|
value = str(value or "").strip()
|
|
|
|
|
|
if not value:
|
|
|
|
|
|
return ""
|
|
|
|
|
|
from urllib.parse import urlparse
|
|
|
|
|
|
|
|
|
|
|
|
parsed = urlparse(value)
|
|
|
|
|
|
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
|
|
|
|
raise ValueError("background 必须是 http(s) 完整 URL 或留空")
|
|
|
|
|
|
# quote()/whitespace would break out of the CSS url('') quoting context
|
|
|
|
|
|
if any(ch in value for ch in ("'", '"', "(", ")", " ", "\\", ";")):
|
|
|
|
|
|
raise ValueError("background URL 含有不允许的字符")
|
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-08-14 01:56:46 +08:00
|
|
|
|
async def get_random_string():
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取随机字符串
|
|
|
|
|
|
:return:
|
|
|
|
|
|
"""
|
2026-06-09 00:53:11 +08:00
|
|
|
|
return "".join(secrets.choice(r_s) for _ in range(5))
|
2023-08-14 05:03:07 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def get_now():
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取当前时间
|
|
|
|
|
|
:return:
|
|
|
|
|
|
"""
|
2025-02-15 22:00:53 +08:00
|
|
|
|
return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))
|
2023-08-24 14:04:00 +08:00
|
|
|
|
|
2023-09-06 11:06:18 +08:00
|
|
|
|
|
2026-07-23 19:38:50 +08:00
|
|
|
|
async def get_select_token(code: str, offset: int = 0):
|
2023-08-24 14:04:00 +08:00
|
|
|
|
"""
|
|
|
|
|
|
获取下载token
|
2026-07-23 19:38:50 +08:00
|
|
|
|
:param code: 取件码
|
|
|
|
|
|
:param offset: 时间窗口偏移(0=当前窗口,1=上一个窗口)。
|
|
|
|
|
|
用于兼容窗口边界竞态:用户在某窗口末尾获取的 token,
|
|
|
|
|
|
请求到达服务器时可能已进入下一窗口。
|
2023-08-24 14:04:00 +08:00
|
|
|
|
:return:
|
|
|
|
|
|
"""
|
2026-06-16 00:49:43 +08:00
|
|
|
|
token = getattr(settings, "jwt_secret", "")
|
|
|
|
|
|
if not token:
|
|
|
|
|
|
raise RuntimeError("应用签名密钥未初始化")
|
2026-07-23 19:38:50 +08:00
|
|
|
|
# 每个窗口约 1000 秒;offset 允许校验上一窗口,避免边界竞态
|
|
|
|
|
|
time_factor = int(time.time() / 1000) - max(0, int(offset))
|
2026-01-07 20:36:59 +08:00
|
|
|
|
return hashlib.sha256(
|
2026-07-23 19:38:50 +08:00
|
|
|
|
f"{code}{time_factor}000{token}".encode()
|
2026-01-07 20:36:59 +08:00
|
|
|
|
).hexdigest()
|
2023-08-24 14:04:00 +08:00
|
|
|
|
|
2023-09-06 11:06:18 +08:00
|
|
|
|
|
|
|
|
|
|
async def get_file_url(code: str):
|
2023-08-24 14:04:00 +08:00
|
|
|
|
"""
|
|
|
|
|
|
对于需要通过服务器中转下载的服务,获取文件下载地址
|
|
|
|
|
|
:param code:
|
|
|
|
|
|
:return:
|
|
|
|
|
|
"""
|
2025-02-15 22:00:53 +08:00
|
|
|
|
return f"/share/download?key={await get_select_token(code)}&code={code}"
|
2023-11-28 10:27:34 +08:00
|
|
|
|
|
2023-12-13 22:50:16 +08:00
|
|
|
|
|
2023-11-28 10:27:34 +08:00
|
|
|
|
async def max_save_times_desc(max_save_seconds: int):
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取最大保存时间的描述
|
|
|
|
|
|
:param max_save_seconds:
|
|
|
|
|
|
:return:
|
|
|
|
|
|
"""
|
2023-12-13 22:50:16 +08:00
|
|
|
|
|
2023-11-28 10:27:34 +08:00
|
|
|
|
def gen_desc_zh(value: int, desc: str):
|
|
|
|
|
|
if value > 0:
|
2025-02-15 22:00:53 +08:00
|
|
|
|
return f"{value}{desc}"
|
2023-11-28 10:27:34 +08:00
|
|
|
|
else:
|
2025-02-15 22:00:53 +08:00
|
|
|
|
return ""
|
2023-12-13 22:50:16 +08:00
|
|
|
|
|
2023-11-28 10:27:34 +08:00
|
|
|
|
def gen_desc_en(value: int, desc: str):
|
|
|
|
|
|
if value > 0:
|
2025-02-15 22:00:53 +08:00
|
|
|
|
ret = f"{value} {desc}"
|
2023-11-28 10:27:34 +08:00
|
|
|
|
if value > 1:
|
2025-02-15 22:00:53 +08:00
|
|
|
|
ret += "s"
|
|
|
|
|
|
ret += " "
|
2023-11-28 10:27:34 +08:00
|
|
|
|
return ret
|
|
|
|
|
|
else:
|
2025-02-15 22:00:53 +08:00
|
|
|
|
return ""
|
2023-12-13 22:50:16 +08:00
|
|
|
|
|
2023-11-28 10:27:34 +08:00
|
|
|
|
max_timedelta = datetime.timedelta(seconds=max_save_seconds)
|
2025-02-15 22:00:53 +08:00
|
|
|
|
desc_zh, desc_en = "最长保存时间:", "Max save time: "
|
|
|
|
|
|
desc_zh += gen_desc_zh(max_timedelta.days, "天")
|
|
|
|
|
|
desc_en += gen_desc_en(max_timedelta.days, "day")
|
|
|
|
|
|
desc_zh += gen_desc_zh(max_timedelta.seconds // 3600, "小时")
|
|
|
|
|
|
desc_en += gen_desc_en(max_timedelta.seconds // 3600, "hour")
|
|
|
|
|
|
desc_zh += gen_desc_zh(max_timedelta.seconds % 3600 // 60, "分钟")
|
|
|
|
|
|
desc_en += gen_desc_en(max_timedelta.seconds % 3600 // 60, "minute")
|
|
|
|
|
|
desc_zh += gen_desc_zh(max_timedelta.seconds % 60, "秒")
|
|
|
|
|
|
desc_en += gen_desc_en(max_timedelta.seconds % 60, "second")
|
2023-11-28 10:27:34 +08:00
|
|
|
|
return desc_zh, desc_en
|
2025-05-21 00:14:40 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-09-09 16:33:07 +08:00
|
|
|
|
# scrypt work factors (OWASP-recommended memory-hard parameters; ~50ms/verify)
|
|
|
|
|
|
SCRYPT_N = 2**14
|
|
|
|
|
|
SCRYPT_R = 8
|
|
|
|
|
|
SCRYPT_P = 1
|
|
|
|
|
|
_SCRYPT_MAXMEM = 64 * 1024 * 1024 # hashlib default cap (32MB) is too low for n=2^14,r=8
|
|
|
|
|
|
|
|
|
|
|
|
PASSWORD_SCHEME = "scrypt" # current scheme for new hashes; sha256/plaintext stay verifiable
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-01-07 20:36:59 +08:00
|
|
|
|
def hash_password(password: str) -> str:
|
|
|
|
|
|
"""
|
2026-09-09 16:33:07 +08:00
|
|
|
|
使用 scrypt(memory-hard)哈希密码
|
|
|
|
|
|
返回格式: scrypt$<n>$<r>$<p>$<salt>$<hash>
|
2026-01-07 20:36:59 +08:00
|
|
|
|
"""
|
|
|
|
|
|
salt = os.urandom(16).hex()
|
2026-09-09 16:33:07 +08:00
|
|
|
|
password_hash = hashlib.scrypt(
|
|
|
|
|
|
password.encode(),
|
|
|
|
|
|
salt=salt.encode(),
|
|
|
|
|
|
n=SCRYPT_N,
|
|
|
|
|
|
r=SCRYPT_R,
|
|
|
|
|
|
p=SCRYPT_P,
|
|
|
|
|
|
maxmem=_SCRYPT_MAXMEM,
|
|
|
|
|
|
).hex()
|
|
|
|
|
|
return f"scrypt${SCRYPT_N}${SCRYPT_R}${SCRYPT_P}${salt}${password_hash}"
|
2026-01-07 20:36:59 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def verify_password(password: str, hashed: str) -> bool:
|
|
|
|
|
|
"""
|
|
|
|
|
|
验证密码是否匹配
|
2026-09-09 16:33:07 +08:00
|
|
|
|
支持格式: scrypt$n$r$p$salt$hash(现行)、sha256$salt$hash(历史)、明文(最老)
|
2026-01-07 20:36:59 +08:00
|
|
|
|
"""
|
|
|
|
|
|
if not hashed:
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
2026-09-09 16:33:07 +08:00
|
|
|
|
if hashed.startswith("scrypt$"):
|
|
|
|
|
|
parts = hashed.split("$")
|
|
|
|
|
|
if len(parts) != 6:
|
|
|
|
|
|
return False
|
|
|
|
|
|
try:
|
|
|
|
|
|
scheme, n, r, p, salt, stored_hash = parts
|
|
|
|
|
|
password_hash = hashlib.scrypt(
|
|
|
|
|
|
password.encode(),
|
|
|
|
|
|
salt=salt.encode(),
|
|
|
|
|
|
n=int(n),
|
|
|
|
|
|
r=int(r),
|
|
|
|
|
|
p=int(p),
|
|
|
|
|
|
maxmem=_SCRYPT_MAXMEM,
|
|
|
|
|
|
).hex()
|
2026-09-14 21:52:23 +08:00
|
|
|
|
# 默认解释器对超范围的 n/r/p 抛 TypeError/ValueError;部分构建会抛
|
|
|
|
|
|
# OverflowError,一并视为校验失败,避免坏掉的存量哈希影响登录路径。
|
|
|
|
|
|
except (ValueError, TypeError, OverflowError):
|
2026-09-09 16:33:07 +08:00
|
|
|
|
return False
|
|
|
|
|
|
return hmac.compare_digest(password_hash, stored_hash)
|
|
|
|
|
|
|
|
|
|
|
|
# sha256 格式: sha256$salt$hash(历史数据,验证逻辑保持原样)
|
2026-01-07 20:36:59 +08:00
|
|
|
|
if hashed.startswith("sha256$"):
|
|
|
|
|
|
parts = hashed.split("$")
|
|
|
|
|
|
if len(parts) != 3:
|
|
|
|
|
|
return False
|
|
|
|
|
|
_, salt, stored_hash = parts
|
|
|
|
|
|
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
|
2026-07-21 14:49:30 +08:00
|
|
|
|
return hmac.compare_digest(password_hash, stored_hash)
|
2026-01-07 20:36:59 +08:00
|
|
|
|
|
|
|
|
|
|
# 旧格式: 明文比较 (兼容迁移前的数据)
|
2026-07-21 14:49:30 +08:00
|
|
|
|
return hmac.compare_digest(str(password), str(hashed))
|
2026-01-07 20:36:59 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def is_password_hashed(password: str) -> bool:
|
|
|
|
|
|
"""
|
2026-09-09 16:33:07 +08:00
|
|
|
|
检查密码是否已经是哈希格式(现行或历史哈希均视为已哈希)
|
2026-01-07 20:36:59 +08:00
|
|
|
|
"""
|
2026-09-09 16:33:07 +08:00
|
|
|
|
if password.startswith("scrypt$") and len(password.split("$")) == 6:
|
|
|
|
|
|
return True
|
2026-01-07 20:36:59 +08:00
|
|
|
|
return password.startswith("sha256$") and len(password.split("$")) == 3
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-09-09 16:33:07 +08:00
|
|
|
|
def password_needs_rehash(hashed: str) -> bool:
|
|
|
|
|
|
"""True when the stored hash uses a legacy scheme (sha256/plaintext)."""
|
|
|
|
|
|
return bool(hashed) and not hashed.startswith(f"{PASSWORD_SCHEME}$")
|
|
|
|
|
|
|
|
|
|
|
|
|
2025-05-21 00:14:40 +08:00
|
|
|
|
async def sanitize_filename(filename: str) -> str:
|
|
|
|
|
|
"""
|
|
|
|
|
|
安全处理文件名:
|
|
|
|
|
|
1. 剥离路径只保留文件名
|
|
|
|
|
|
2. 替换非法字符
|
|
|
|
|
|
3. 处理空文件名情况
|
|
|
|
|
|
"""
|
|
|
|
|
|
filename = os.path.basename(filename)
|
|
|
|
|
|
illegal_chars = r'[\\/*?:"<>|\x00-\x1F]' # 包含控制字符
|
|
|
|
|
|
# 替换非法字符为下划线
|
2026-01-07 20:36:59 +08:00
|
|
|
|
cleaned = re.sub(illegal_chars, "_", filename)
|
2025-05-21 00:14:40 +08:00
|
|
|
|
# 处理空格(可选替换为_)
|
2026-01-07 20:36:59 +08:00
|
|
|
|
cleaned = cleaned.replace(" ", "_")
|
2025-05-21 00:14:40 +08:00
|
|
|
|
# 处理连续下划线
|
2026-01-07 20:36:59 +08:00
|
|
|
|
cleaned = re.sub(r"_+", "_", cleaned)
|
2025-05-21 00:14:40 +08:00
|
|
|
|
# 处理首尾特殊字符
|
2026-01-07 20:36:59 +08:00
|
|
|
|
cleaned = cleaned.strip("._")
|
2025-05-21 00:14:40 +08:00
|
|
|
|
# 处理空文件名情况
|
|
|
|
|
|
if not cleaned:
|
2026-01-07 20:36:59 +08:00
|
|
|
|
cleaned = "unnamed_file"
|
2025-05-21 00:14:40 +08:00
|
|
|
|
# 长度限制(按需调整)
|
|
|
|
|
|
return cleaned[:255]
|