2026-11-20 01:35:46 +08:00
|
|
|
"""HTTP, authentication and file transfer for LightCore applications."""
|
|
|
|
|
import contextlib
|
|
|
|
|
import errno
|
|
|
|
|
import getpass
|
2026-11-20 04:02:32 +08:00
|
|
|
from hashlib import sha256
|
2026-11-20 01:35:46 +08:00
|
|
|
from http.client import IncompleteRead
|
|
|
|
|
import ipaddress
|
|
|
|
|
import json
|
|
|
|
|
import mimetypes
|
|
|
|
|
import os
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
import re
|
2026-11-20 04:02:32 +08:00
|
|
|
import stat
|
2026-11-20 01:35:46 +08:00
|
|
|
import subprocess
|
|
|
|
|
import sys
|
|
|
|
|
import tempfile
|
|
|
|
|
import time
|
|
|
|
|
from urllib.error import HTTPError, URLError
|
|
|
|
|
from urllib.parse import urlsplit
|
|
|
|
|
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
|
|
|
from uuid import uuid4
|
|
|
|
|
|
|
|
|
|
DEFAULT_BASE_URL = 'https://api.zhecent.com'
|
|
|
|
|
DEFAULT_BASE_URLS = {'shop': DEFAULT_BASE_URL, 'media': DEFAULT_BASE_URL,
|
2026-11-20 04:02:32 +08:00
|
|
|
'gysmart': 'https://am.gysmart.shop', 'fangyus': '', 'hengde': ''}
|
2026-11-20 01:35:46 +08:00
|
|
|
APP_KEY = 'LIGHTCORE_API_APP'
|
|
|
|
|
KEYS = ('LIGHTCORE_API_BASE_URL', 'LIGHTCORE_ACCESS_TOKEN', 'LIGHTCORE_REFRESH_TOKEN',
|
|
|
|
|
'LIGHTCORE_ACCESS_TOKEN_EXPIRES_AT', 'LIGHTCORE_REFRESH_TOKEN_EXPIRES_AT')
|
|
|
|
|
AUTH_FIELDS = dict(zip(KEYS[1:], ('accessToken', 'refreshToken', 'accessTokenExpiresAt', 'refreshTokenExpiresAt')))
|
|
|
|
|
SECRET_FIELDS = {'password', 'oldpassword', 'newpassword', 'token', 'accesstoken', 'refreshtoken',
|
|
|
|
|
'clientsecret', 'secret', 'authorization', 'cookie', 'setcookie', 'privatekey',
|
|
|
|
|
'apikey', 'appkey', 'jwtsecret', 'credentials', 'idtoken', 'proxyauthorization'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ClientError(Exception):
|
|
|
|
|
def __init__(self, message, **details):
|
|
|
|
|
super().__init__(message)
|
|
|
|
|
self.details = details
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class NoRedirect(HTTPRedirectHandler):
|
|
|
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def base_url(value, app="shop"):
|
|
|
|
|
value = (value or '').strip() or DEFAULT_BASE_URLS[app]
|
|
|
|
|
try:
|
|
|
|
|
url = urlsplit(value)
|
|
|
|
|
loopback = url.hostname == 'localhost'
|
|
|
|
|
try:
|
|
|
|
|
loopback = loopback or ipaddress.ip_address(url.hostname).is_loopback
|
|
|
|
|
except ValueError:
|
|
|
|
|
pass
|
|
|
|
|
valid = (url.hostname and url.port != 0 and not url.username and not url.password
|
|
|
|
|
and not url.query and not url.fragment and url.path.rstrip('/') in ('', admin_path(app))
|
|
|
|
|
and (url.scheme == 'https' or (url.scheme == 'http' and loopback)))
|
|
|
|
|
if valid and not re.search(r'\s', value):
|
|
|
|
|
return url._replace(path='').geturl()
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
pass
|
|
|
|
|
raise ClientError('服务地址必须是 HTTPS 域名或当前应用后台地址;仅本机测试允许 HTTP。')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def admin_path(app):
|
|
|
|
|
return '/api/admin' if app == 'system' else f'/api/{app}/admin'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def protect_file(path):
|
|
|
|
|
"""临时文件写入凭证之前设置权限;Windows 使用系统内置权限工具。"""
|
|
|
|
|
if os.name == 'nt':
|
|
|
|
|
import ctypes
|
|
|
|
|
directory = ctypes.create_unicode_buffer(32768)
|
|
|
|
|
if not ctypes.windll.kernel32.GetSystemDirectoryW(directory, len(directory)):
|
|
|
|
|
raise ClientError('无法确定 Windows 系统工具位置。')
|
|
|
|
|
tools = Path(directory.value)
|
|
|
|
|
identity = subprocess.run([str(tools / 'whoami.exe'), '/user', '/fo', 'csv', '/nh'],
|
|
|
|
|
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
|
|
|
|
|
sid = re.search(rb'S-\d-\d+(?:-\d+)+', identity.stdout)
|
|
|
|
|
if not sid:
|
|
|
|
|
raise ClientError('无法确认当前 Windows 用户的文件权限。')
|
|
|
|
|
subprocess.run([str(tools / 'icacls.exe'), str(path), '/inheritance:r', '/grant:r',
|
|
|
|
|
'*' + sid[0].decode('ascii') + ':(F)'], capture_output=True, check=True,
|
|
|
|
|
creationflags=subprocess.CREATE_NO_WINDOW)
|
|
|
|
|
else:
|
|
|
|
|
os.chmod(path, 0o600)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def private_write(path, content):
|
|
|
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
fd, temporary = tempfile.mkstemp(prefix=path.name + '.', suffix='.tmp', dir=path.parent)
|
|
|
|
|
os.close(fd)
|
|
|
|
|
temporary = Path(temporary)
|
|
|
|
|
try:
|
|
|
|
|
protect_file(temporary)
|
|
|
|
|
with temporary.open('w', encoding='utf-8', newline='') as stream:
|
|
|
|
|
stream.write(content)
|
|
|
|
|
stream.flush()
|
|
|
|
|
os.fsync(stream.fileno())
|
|
|
|
|
os.replace(temporary, path)
|
|
|
|
|
finally:
|
|
|
|
|
temporary.unlink(missing_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
|
def private_output(path):
|
|
|
|
|
target = Path(path).absolute()
|
|
|
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
fd, name = tempfile.mkstemp(prefix=target.name + '.', suffix='.tmp', dir=target.parent)
|
|
|
|
|
os.close(fd)
|
|
|
|
|
temporary = Path(name)
|
|
|
|
|
try:
|
|
|
|
|
protect_file(temporary)
|
|
|
|
|
with temporary.open('wb') as stream:
|
|
|
|
|
yield stream
|
|
|
|
|
stream.flush()
|
|
|
|
|
os.fsync(stream.fileno())
|
|
|
|
|
os.link(temporary, target) # 同目录原子创建,拒绝覆盖。
|
|
|
|
|
finally:
|
|
|
|
|
temporary.unlink(missing_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
|
def session_lock(path, timeout):
|
|
|
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
with Path(str(path) + '.lock').open('a+b') as stream:
|
|
|
|
|
protect_file(Path(str(path) + '.lock'))
|
|
|
|
|
if os.fstat(stream.fileno()).st_size == 0:
|
|
|
|
|
stream.write(b'\0')
|
|
|
|
|
stream.flush()
|
|
|
|
|
until = time.monotonic() + timeout + 5
|
|
|
|
|
while True:
|
|
|
|
|
try:
|
|
|
|
|
if os.name == 'nt':
|
|
|
|
|
import msvcrt
|
|
|
|
|
stream.seek(0)
|
|
|
|
|
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
|
|
|
|
|
else:
|
|
|
|
|
import fcntl
|
|
|
|
|
fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
|
|
|
break
|
|
|
|
|
except OSError as error:
|
|
|
|
|
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
|
|
|
|
|
raise
|
|
|
|
|
if time.monotonic() >= until:
|
|
|
|
|
raise ClientError('等待会话锁超时;未发送业务请求。') from None
|
|
|
|
|
time.sleep(0.1)
|
|
|
|
|
try:
|
|
|
|
|
yield
|
|
|
|
|
finally:
|
|
|
|
|
if os.name == 'nt':
|
|
|
|
|
stream.seek(0)
|
|
|
|
|
msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
|
|
|
|
|
else:
|
|
|
|
|
fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def compact(value):
|
|
|
|
|
return json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def reject_constant(_):
|
|
|
|
|
raise ValueError('非标准 JSON 常量')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class MultipartBody:
|
|
|
|
|
"""可重复打开的有长度流;仅认证失效允许一次重发。"""
|
2026-11-20 04:02:32 +08:00
|
|
|
def __init__(self, file, fields, *, reject_symlink=False):
|
|
|
|
|
self.file = Path(file).absolute() if reject_symlink else Path(file).resolve()
|
|
|
|
|
self.reject_symlink = reject_symlink
|
2026-11-20 01:35:46 +08:00
|
|
|
if not isinstance(fields, dict) or any(not isinstance(k, str) or not isinstance(v, (str, int, float, bool)) for k, v in fields.items()):
|
|
|
|
|
raise ClientError('上传表单必须是 JSON 对象,字段值为字符串、数字或布尔值。')
|
2026-11-20 04:02:32 +08:00
|
|
|
self.stat = self.file.lstat() if self.reject_symlink else self.file.stat()
|
|
|
|
|
if not stat.S_ISREG(self.stat.st_mode):
|
|
|
|
|
raise ClientError('上传路径必须是普通文件。')
|
2026-11-20 01:35:46 +08:00
|
|
|
boundary = 'lightcore-' + uuid4().hex
|
|
|
|
|
self.content_type = 'multipart/form-data; boundary=' + boundary
|
|
|
|
|
parts = []
|
|
|
|
|
for key, value in fields.items():
|
|
|
|
|
if any(c in key for c in '\r\n"'):
|
|
|
|
|
raise ClientError('上传字段名无效。')
|
|
|
|
|
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n')
|
|
|
|
|
name = self.file.name.replace('"', '_').replace('\r', '_').replace('\n', '_')
|
|
|
|
|
# Windows MIME registration may omit WebP or override its standard type.
|
|
|
|
|
mime = ('image/webp' if self.file.suffix.lower() == '.webp'
|
|
|
|
|
else mimetypes.guess_type(name)[0] or 'application/octet-stream')
|
|
|
|
|
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{name}"\r\nContent-Type: {mime}\r\n\r\n')
|
|
|
|
|
self.prefix = ''.join(parts).encode('utf-8')
|
|
|
|
|
self.suffix = f'\r\n--{boundary}--\r\n'.encode('ascii')
|
|
|
|
|
self.size = len(self.prefix) + self.stat.st_size + len(self.suffix)
|
|
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
|
with self.file.open('rb') as stream:
|
2026-11-20 04:02:32 +08:00
|
|
|
current = os.fstat(stream.fileno())
|
|
|
|
|
if (not os.path.samestat(current, self.stat)
|
|
|
|
|
or current.st_size != self.stat.st_size or current.st_mtime_ns != self.stat.st_mtime_ns
|
|
|
|
|
or self.reject_symlink and self.file.is_symlink()):
|
|
|
|
|
raise ClientError('上传文件已变化,未继续发送。')
|
|
|
|
|
yield self.prefix
|
2026-11-20 01:35:46 +08:00
|
|
|
while chunk := stream.read(1024 * 1024):
|
|
|
|
|
yield chunk
|
|
|
|
|
yield self.suffix
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Client:
|
|
|
|
|
secret_fields = SECRET_FIELDS
|
|
|
|
|
|
|
|
|
|
def __init__(self, app, env_file, timeout=30):
|
|
|
|
|
self.app = app
|
|
|
|
|
self.timeout = timeout
|
2026-11-20 04:02:32 +08:00
|
|
|
self.refreshable = self.app in ('shop', 'media', 'fangyus', 'hengde')
|
2026-11-20 01:35:46 +08:00
|
|
|
self.auth_fields = {key: field for key, field in AUTH_FIELDS.items()
|
|
|
|
|
if self.refreshable or key in (KEYS[1], KEYS[3])}
|
|
|
|
|
self.admin_path = admin_path(app)
|
|
|
|
|
self.env = Path(env_file).resolve()
|
|
|
|
|
self.secrets = []
|
|
|
|
|
self.refreshed = False
|
|
|
|
|
self.http = build_opener(NoRedirect())
|
|
|
|
|
|
|
|
|
|
def redact(self, text):
|
|
|
|
|
for secret in self.secrets:
|
|
|
|
|
if secret:
|
|
|
|
|
for encoded in {secret, json.dumps(secret, ensure_ascii=False)[1:-1],
|
|
|
|
|
json.dumps(secret, ensure_ascii=True)[1:-1]}:
|
|
|
|
|
text = text.replace(encoded, '[REDACTED]')
|
|
|
|
|
return text
|
|
|
|
|
|
|
|
|
|
def remember_secrets(self, value):
|
|
|
|
|
if isinstance(value, dict):
|
|
|
|
|
for key, item in value.items():
|
|
|
|
|
normalized = re.sub(r'[^a-z]', '', key.lower())
|
|
|
|
|
sensitive = (normalized in self.secret_fields or 'password' in normalized
|
|
|
|
|
or normalized.endswith(('authorization', 'apikey', 'appkey', 'jwtsecret', 'clientsecret', 'privatekey', 'token')))
|
|
|
|
|
if sensitive and isinstance(item, str) and item:
|
|
|
|
|
self.secrets.append(item)
|
|
|
|
|
self.remember_secrets(item)
|
|
|
|
|
elif isinstance(value, list):
|
|
|
|
|
for item in value:
|
|
|
|
|
self.remember_secrets(item)
|
|
|
|
|
|
|
|
|
|
def read_settings(self):
|
|
|
|
|
if not self.env.is_file():
|
|
|
|
|
return {}
|
|
|
|
|
settings = {}
|
|
|
|
|
for line in self.env.read_text(encoding='utf-8-sig').splitlines():
|
|
|
|
|
match = re.fullmatch(r'\s*([A-Z_]+)\s*=(.*)', line)
|
|
|
|
|
if match and match[1] in KEYS + (APP_KEY,):
|
|
|
|
|
if match[1] in settings:
|
|
|
|
|
raise ClientError('会话文件存在重复键,请重新登录。')
|
|
|
|
|
value = match[2].strip()
|
|
|
|
|
if len(value) >= 2 and value[0] in ('"', "'") and value[-1] == value[0]:
|
|
|
|
|
value = value[1:-1]
|
|
|
|
|
settings[match[1]] = value
|
|
|
|
|
return settings
|
|
|
|
|
|
|
|
|
|
def configured_base(self, settings, explicit=None):
|
|
|
|
|
candidates = (explicit, os.environ.get(KEYS[0]), settings.get(KEYS[0]))
|
2026-11-20 04:02:32 +08:00
|
|
|
address = next((value for value in candidates if value and value.strip()), DEFAULT_BASE_URLS[self.app])
|
|
|
|
|
if not address:
|
|
|
|
|
raise ClientError('首次登录请通过 --base-url 指定目标后端地址。')
|
|
|
|
|
return base_url(address, self.app)
|
2026-11-20 01:35:46 +08:00
|
|
|
|
|
|
|
|
def read_session(self):
|
|
|
|
|
if not self.env.is_file():
|
|
|
|
|
raise ClientError('尚未登录,请先手动运行 login。')
|
|
|
|
|
session = self.read_settings()
|
|
|
|
|
if session.get(APP_KEY) != self.app:
|
|
|
|
|
raise ClientError("会话不属于当前应用,请选择正确的 --app 或重新登录。")
|
|
|
|
|
if any(not session.get(key) for key in self.auth_fields):
|
|
|
|
|
raise ClientError('会话文件不完整,请重新登录。')
|
|
|
|
|
self.secrets.extend(session[key] for key in self.auth_fields if key in KEYS[1:3])
|
|
|
|
|
if any(not session[key].isdigit() or int(session[key]) <= 0 for key in self.auth_fields if key in KEYS[3:]):
|
|
|
|
|
raise ClientError('会话过期时间无效,请重新登录。')
|
|
|
|
|
configured = self.configured_base(session)
|
|
|
|
|
if session.get(KEYS[0], '').strip() and base_url(session[KEYS[0]], self.app) != configured:
|
|
|
|
|
raise ClientError('服务地址与已登录会话不同,请先运行 login。')
|
|
|
|
|
session[KEYS[0]] = configured
|
|
|
|
|
return session
|
|
|
|
|
|
|
|
|
|
def write_session(self, session):
|
|
|
|
|
lines = self.env.read_text(encoding='utf-8-sig').splitlines() if self.env.exists() else []
|
|
|
|
|
lines = [line for line in lines if not ((match := re.match(r'\s*([A-Z_]+)\s*=', line)) and match[1] in KEYS + (APP_KEY,))]
|
|
|
|
|
for key in (KEYS[0], *self.auth_fields):
|
|
|
|
|
value = session[key]
|
|
|
|
|
if not value or '\r' in value or '\n' in value:
|
|
|
|
|
raise ClientError('服务返回了无效会话,未保存。')
|
|
|
|
|
lines.append(f'{key}={value}')
|
|
|
|
|
lines.append(f'{APP_KEY}={self.app}')
|
|
|
|
|
private_write(self.env, '\n'.join(lines) + '\n')
|
|
|
|
|
|
|
|
|
|
def save_download(self, response, output):
|
|
|
|
|
details = {'httpStatus': response.status, 'code': 200,
|
|
|
|
|
'traceId': response.headers.get('X-Request-ID')}
|
|
|
|
|
target = Path(output).absolute()
|
2026-11-20 04:02:32 +08:00
|
|
|
digest = sha256()
|
2026-11-20 01:35:46 +08:00
|
|
|
try:
|
|
|
|
|
size = 0
|
|
|
|
|
with private_output(target) as stream:
|
|
|
|
|
while chunk := response.read(1024 * 1024):
|
|
|
|
|
stream.write(chunk)
|
2026-11-20 04:02:32 +08:00
|
|
|
digest.update(chunk)
|
2026-11-20 01:35:46 +08:00
|
|
|
size += len(chunk)
|
|
|
|
|
expected = response.headers.get('Content-Length')
|
|
|
|
|
if expected is not None and size != int(expected):
|
|
|
|
|
raise ClientError('下载长度不完整,未保存目标文件。', **details)
|
2026-11-20 04:02:32 +08:00
|
|
|
return {'ok': True, **details, 'downloaded': True, 'outputFile': str(target),
|
|
|
|
|
'bytes': size, 'sha256': digest.hexdigest()}
|
2026-11-20 01:35:46 +08:00
|
|
|
except (OSError, ValueError, IncompleteRead, subprocess.SubprocessError) as error:
|
|
|
|
|
raise ClientError('下载未完成或目标文件已存在;未覆盖目标文件。', **details) from error
|
|
|
|
|
|
|
|
|
|
def send(self, base, path, payload, token='', method='POST', output=None):
|
|
|
|
|
headers = {'Accept': 'application/json', 'Content-Type': 'application/json; charset=utf-8',
|
|
|
|
|
'User-Agent': 'lightcore-api/1.0'}
|
|
|
|
|
if token:
|
|
|
|
|
headers['Authorization'] = 'Bearer ' + token
|
|
|
|
|
if isinstance(payload, MultipartBody):
|
|
|
|
|
headers['Content-Type'] = payload.content_type
|
|
|
|
|
headers['Content-Length'] = str(payload.size)
|
|
|
|
|
request = Request(base + self.admin_path + path, data=payload, headers=headers, method=method)
|
2026-11-20 04:02:32 +08:00
|
|
|
trace_id = None
|
2026-11-20 01:35:46 +08:00
|
|
|
try:
|
|
|
|
|
try:
|
|
|
|
|
response = self.http.open(request, timeout=self.timeout)
|
|
|
|
|
except HTTPError as error:
|
|
|
|
|
response = error
|
|
|
|
|
with response:
|
2026-11-20 04:02:32 +08:00
|
|
|
trace_id = response.headers.get('X-Request-ID')
|
2026-11-20 01:35:46 +08:00
|
|
|
if (output is not None and 200 <= response.status < 300
|
|
|
|
|
and response.headers.get('Content-Disposition', '').lower().startswith('attachment')
|
|
|
|
|
and (self.app != 'system' or response.headers.get_content_type() == 'application/zip')):
|
|
|
|
|
return self.save_download(response, output)
|
|
|
|
|
raw = response.read().decode(response.headers.get_content_charset() or 'utf-8')
|
|
|
|
|
status = response.status
|
|
|
|
|
except (URLError, OSError, TimeoutError, IncompleteRead, ValueError):
|
2026-11-20 04:02:32 +08:00
|
|
|
details = {'traceId': trace_id} if trace_id else {}
|
|
|
|
|
raise ClientError('HTTP 请求未获得完整响应,结果未知;写操作请先核对业务结果,不要盲目重试。', **details) from None
|
2026-11-20 01:35:46 +08:00
|
|
|
parsed = None
|
|
|
|
|
try:
|
|
|
|
|
parsed = json.loads(raw)
|
|
|
|
|
except ValueError:
|
|
|
|
|
pass
|
|
|
|
|
code = parsed.get('code') if isinstance(parsed, dict) else None
|
|
|
|
|
return {'httpStatus': status, 'code': code, 'traceId': trace_id, 'raw': raw, 'json': parsed}
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def success(response):
|
|
|
|
|
return 200 <= response['httpStatus'] < 300 and response['code'] == 200
|
|
|
|
|
|
|
|
|
|
def auth_session(self, base, response):
|
|
|
|
|
details = {key: response[key] for key in ('httpStatus', 'code', 'traceId')}
|
|
|
|
|
if not self.success(response):
|
|
|
|
|
raise ClientError('登录或刷新失败,请手动登录。', **details)
|
|
|
|
|
data = response['json'].get('data')
|
|
|
|
|
if not isinstance(data, dict) or any(not data.get(field) for field in self.auth_fields.values()):
|
|
|
|
|
raise ClientError('认证响应不完整,未保存会话。', **details)
|
|
|
|
|
self.remember_secrets(data)
|
|
|
|
|
if any(not str(data[field]).isdigit() or int(data[field]) <= time.time()
|
|
|
|
|
for key, field in self.auth_fields.items() if key in KEYS[3:]):
|
|
|
|
|
raise ClientError('认证响应过期时间无效,未保存会话。', **details)
|
|
|
|
|
return {KEYS[0]: base, **{key: str(data[field]) for key, field in self.auth_fields.items()}}
|
|
|
|
|
|
|
|
|
|
def request_session(self, failed_token=None, expected_base=None, *, force_refresh=False):
|
|
|
|
|
with session_lock(self.env, self.timeout):
|
|
|
|
|
session = self.read_session()
|
|
|
|
|
if expected_base and session[KEYS[0]] != expected_base:
|
|
|
|
|
raise ClientError('会话服务地址已变更,请重新发起请求。')
|
|
|
|
|
if not self.refreshable:
|
|
|
|
|
if int(session[KEYS[3]]) <= time.time():
|
|
|
|
|
raise ClientError('会话已过期,请手动运行 login 重新登录。')
|
|
|
|
|
return session
|
|
|
|
|
needs_refresh = force_refresh or (session[KEYS[1]] == failed_token if failed_token is not None
|
|
|
|
|
else int(session[KEYS[3]]) <= time.time() + 30)
|
|
|
|
|
if needs_refresh:
|
|
|
|
|
if self.refreshed:
|
|
|
|
|
raise ClientError('本次请求已刷新过会话,请手动登录后核对。')
|
|
|
|
|
if int(session[KEYS[4]]) <= time.time():
|
|
|
|
|
raise ClientError('会话已过期,请手动登录。')
|
|
|
|
|
self.refreshed = True
|
|
|
|
|
response = self.send(session[KEYS[0]], '/auth/refresh',
|
|
|
|
|
compact({'refreshToken': session[KEYS[2]]}).encode('utf-8'))
|
|
|
|
|
session = self.auth_session(session[KEYS[0]], response)
|
|
|
|
|
self.write_session(session)
|
|
|
|
|
return session
|
|
|
|
|
|
|
|
|
|
def refresh(self):
|
|
|
|
|
self.refreshed = False
|
|
|
|
|
self.request_session(force_refresh=True)
|
|
|
|
|
return {'ok': True, 'message': '已刷新本机会话。'}
|
|
|
|
|
|
|
|
|
|
def logout(self):
|
|
|
|
|
self.refreshed = False
|
|
|
|
|
self.request_session()
|
|
|
|
|
with session_lock(self.env, self.timeout):
|
|
|
|
|
session = self.read_session()
|
|
|
|
|
response = self.send(
|
|
|
|
|
session[KEYS[0]], '/auth/logout',
|
|
|
|
|
compact({'refreshToken': session[KEYS[2]]}).encode('utf-8'), session[KEYS[1]],
|
|
|
|
|
)
|
|
|
|
|
details = {key: response[key] for key in ('httpStatus', 'code', 'traceId')}
|
|
|
|
|
if not self.success(response):
|
|
|
|
|
raise ClientError('退出失败,本机会话文件尚未更新。', **details)
|
|
|
|
|
self.clear_session(details)
|
|
|
|
|
return {'ok': True, **details}
|
|
|
|
|
|
|
|
|
|
def clear_session(self, details):
|
|
|
|
|
try:
|
|
|
|
|
lines = self.env.read_text(encoding='utf-8-sig').splitlines()
|
|
|
|
|
remaining = [line for line in lines if line.partition('=')[0].strip() not in self.auth_fields]
|
|
|
|
|
private_write(self.env, '\n'.join(remaining) + '\n')
|
|
|
|
|
except (OSError, subprocess.SubprocessError, ClientError) as error:
|
|
|
|
|
raise ClientError('服务端已退出,但清理本机会话失败。', **details) from error
|
|
|
|
|
|
2026-11-20 04:02:32 +08:00
|
|
|
def login_base(self, explicit_base, isolate_target=False):
|
2026-11-20 01:35:46 +08:00
|
|
|
previous = self.read_settings()
|
|
|
|
|
if previous.get(APP_KEY) not in (None, self.app) or (previous.get(APP_KEY) is None and any(previous.get(k) for k in KEYS[1:])):
|
|
|
|
|
raise ClientError('目标文件已有其他或未标明应用的会话,拒绝覆盖,请使用独立会话文件。')
|
2026-11-20 04:02:32 +08:00
|
|
|
base = self.configured_base(previous, explicit_base)
|
|
|
|
|
if (isolate_target and previous.get(KEYS[0]) and previous.get(KEYS[1])
|
|
|
|
|
and base_url(previous[KEYS[0]], self.app) != base):
|
|
|
|
|
raise ClientError('会话文件属于其他目标后端,请通过 --env-file 指定独立文件。')
|
|
|
|
|
return base
|
2026-11-20 01:35:46 +08:00
|
|
|
|
2026-11-20 04:02:32 +08:00
|
|
|
def login(self, explicit_base=None, *, isolate_target=False):
|
|
|
|
|
base = self.login_base(explicit_base, isolate_target)
|
2026-11-20 01:35:46 +08:00
|
|
|
account_field = 'identifier' if self.app == 'shop' else 'username'
|
|
|
|
|
while True:
|
|
|
|
|
identifier = input('后台账号或登录手机号: ')
|
|
|
|
|
password = getpass.getpass('后台密码: ')
|
|
|
|
|
self.secrets.append(password)
|
|
|
|
|
payload = compact({account_field: identifier, 'password': password}).encode('utf-8')
|
|
|
|
|
response = self.send(base, '/auth/login', payload)
|
|
|
|
|
result = response['json']
|
|
|
|
|
if (self.app == 'media' and response['httpStatus'] == 200 and response['code'] == 400
|
|
|
|
|
and result.get('msg') == '用户名或密码错误'):
|
|
|
|
|
self.secrets.pop()
|
|
|
|
|
print('用户名或密码错误,请重新输入账号和密码。按 Ctrl+C 取消。', file=sys.stderr)
|
|
|
|
|
continue
|
|
|
|
|
break
|
|
|
|
|
session = self.auth_session(base, response)
|
|
|
|
|
with session_lock(self.env, self.timeout):
|
2026-11-20 04:02:32 +08:00
|
|
|
self.login_base(base, isolate_target)
|
2026-11-20 01:35:46 +08:00
|
|
|
self.write_session(session)
|
|
|
|
|
return {'ok': True, 'traceId': response['traceId'], 'message': '登录成功,会话已保存在本机。'}
|
|
|
|
|
|
|
|
|
|
def exchange(self, path, payload, method='POST', output=None):
|
|
|
|
|
self.refreshed = False
|
|
|
|
|
if not re.fullmatch(r'/[A-Za-z0-9/_-]+', path) or path.startswith('//'):
|
|
|
|
|
raise ClientError('path 必须是后台相对接口路径,例如 /content/social/getContentList。')
|
|
|
|
|
if re.fullmatch(r'/auth/(login|refresh)/?', path):
|
|
|
|
|
raise ClientError('认证接口由 login 和会话刷新处理,不作为普通请求输出。')
|
|
|
|
|
if output is not None and (Path(output).exists() or Path(output).is_symlink()):
|
|
|
|
|
raise ClientError('目标文件已存在,拒绝覆盖。')
|
|
|
|
|
session = self.request_session()
|
|
|
|
|
response = self.send(session[KEYS[0]], path, payload, session[KEYS[1]], method, output)
|
|
|
|
|
if not self.refreshable and (response['httpStatus'] == 401 or response['code'] == 1001):
|
|
|
|
|
raise ClientError('会话已失效,请手动运行 login 重新登录;未重试业务请求。',
|
|
|
|
|
**{key: response[key] for key in ('httpStatus', 'code', 'traceId')})
|
|
|
|
|
if (response['httpStatus'] == 401 or response['code'] == 1001) and not self.refreshed:
|
|
|
|
|
session = self.request_session(session[KEYS[1]], session[KEYS[0]])
|
|
|
|
|
response = self.send(session[KEYS[0]], path, payload, session[KEYS[1]], method, output)
|
|
|
|
|
self.remember_secrets(response.get('json'))
|
|
|
|
|
return response
|