feat: 新增 lightcore-cli 命令行工具项目

新增完整的 lightcore-cli 命令行工具代码,包含:
- CLI 入口与参数解析
- System 和 Media 应用的客户端实现
- 丰富的子命令与操作接口
- 测试用例与项目配置
- .gitignore 与 README 文档
This commit is contained in:
2026-11-20 01:35:46 +08:00
commit 3eb720cfbd
17 changed files with 2862 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
__pycache__/
*.py[cod]
*.egg-info/
.venv/
.pytest_cache/
.work/
.env
.env.*
*.env
*.pem
*.key
build/
dist/
+91
View File
@@ -0,0 +1,91 @@
# LightCore CLI
LightCore CLI 提供 System、Media 和其他 LightCore 应用的后台命令。
## 安装
使用 Python 3.10 或更新版本。从远程仓库安装需要 Git。
```powershell
python -m pip install "lightcore-cli @ git+https://code.zhecent.com/open/lightcore-cli.git"
lightcore --help
```
从已克隆的源码安装时,在仓库根目录运行 `python -m pip install .`。
## 登录与会话
独立安装时,CLI 将各应用的会话存到用户目录下的 `.lightcore/lightcore-api/<应用>/.env`。例如 System 使用 `system/.env`,Media 使用 `media/.env`。从 LightCore 或相邻的 plan 工作区执行时,CLI 使用 LightCore 下的 `.work/lightcore-api/<应用>/.env`。可在应用名后传 `--env-file` 指定会话文件,登录和后续命令使用同一路径。
System 首次登录时指定目标后端。将示例域名换成实际地址,在终端中按提示输入管理员账号和密码。
```powershell
lightcore system login --base-url https://system.example.com
lightcore media login
lightcore system --help
lightcore media --help
lightcore api --help
```
Media 拒绝账号或密码时会重新提示输入,按 `Ctrl+C` 可取消。
## System
使用独立会话文件连接本地开发实例。
```powershell
lightcore system --env-file .work/system-local.env login --base-url http://localhost:8888
lightcore system --env-file .work/system-local.env monitor server
lightcore system trace detail --help
lightcore system storage-clients create --example
```
完整操作从 `lightcore system --help` 查找。凭据、对象访问 URL 和证书下载使用 `--output` 保存到私有文件。
## Media
```text
lightcore media files find --keyword "推窗器"
lightcore media files list --document-id 58
lightcore media files upload "推窗器说明书.pdf"
lightcore media files get --document-id 58 --file-id 123 --file-id 124
```
`find` 返回文档 ID 和标题。上传返回 `fileId`,可以在 Media 里关联到产品文档。下载按文档验证附件,默认写到执行目录的 `.work/media/58/`。每项结果包含文件 ID 与保存路径,遇到同名目标时报告失败。命令参数和示例通过相应的 `--help` 查看。
上传响应超时后,核对原操作再使用错误输出中的 `requestId` 发起重试。临时下载、应用会话和本机配置留在使用设备。不同用户用自己的 Media 账号登录。
Media 的子命令覆盖后台登录、刷新和退出、个人资料、管理员、社媒账号、稿件、参考内容、发布登记、文档、短剧、文件和存储绑定。
从 `lightcore media --help` 找命令组,在具体命令末尾加 `--help` 查参数。例如 `contents list --help` 显示 `--page-size` 范围 1–100、默认 20,以及 `--content-type` 的可选值。
```text
lightcore media contents list --help
lightcore media videos save --schema
lightcore media videos save --example
lightcore media videos save --example update
```
接受 JSON 的命令提供 `--schema` 和 `--example`,无需会话即可查看。字段说明包含类型、枚举、嵌套结构和必填条件。示例中的 ID、正文和时间是占位内容,更新前读取实际记录的 ID 和 `updatedAt`。填写后用 `--body-file` 提交 UTF-8 JSON。涉及密码或存储密钥时,使用本机私有文件。跨字段约束、权限和服务端校验以对应应用契约为准。
```text
lightcore media accounts list --page-size 20
lightcore media projects context --project-id 58
lightcore media contents save --body-file .work/content.json
lightcore media videos download --video-id 58 --file-id 123 --output .work/参考图.png
```
## 通用 HTTP
其他应用可通过 `lightcore api` 调用。按应用契约填写后台相对路径和 JSON。不同应用使用各自会话。
```text
lightcore api login --app gysmart
lightcore api request --app gysmart --path /product/getList --body-file .work/products-query.json
```
从当前工作目录接收 `responseFile` 摘要时,读取 CLI 返回的完整响应文件以获取截断部分。
## 测试
在本目录运行 `python -m unittest discover -s tests`,使用本机 HTTP 服务验证命令。与 Go 后台路由的比对需要完整 LightCore 源码。
+1
View File
@@ -0,0 +1 @@
"""Command-line client for LightCore applications."""
+3
View File
@@ -0,0 +1,3 @@
from .cli import main
raise SystemExit(main())
+103
View File
@@ -0,0 +1,103 @@
"""通用后台 HTTP 命令。"""
import json
from pathlib import Path
import subprocess
from uuid import uuid4
from . import transport
from .transport import ClientError, compact, private_write
class RawClient(transport.Client):
def __init__(self, args, response_dir):
super().__init__(args.app, args.env_file, args.timeout)
self.args = args
self.response_dir = response_dir
def request(self):
payload = (Path(self.args.body_file).read_bytes() if self.args.body_file
else (self.args.body if self.args.body is not None else '{}').encode('utf-8'))
try:
body = json.loads(payload.decode('utf-8-sig'), parse_constant=transport.reject_constant)
except (ValueError, UnicodeError):
raise ClientError('请求正文必须是有效 JSON。') from None
self.remember_secrets(body)
if self.args.action == 'upload':
payload = transport.MultipartBody(self.args.file, body)
response = self.exchange(self.args.path, payload, self.args.method, self.args.output)
return format_response(self, response, self.response_dir, self.args.max_chars)
def format_response(client, response, response_dir, max_chars=6000):
if response.get('downloaded'):
return response
raw = client.redact(response['raw'])
try:
body = json.loads(raw)
except ValueError:
body = raw
result = {'ok': client.success(response), 'httpStatus': response['httpStatus'], 'code': response['code'],
'traceId': response['traceId'], 'truncated': False, 'body': body}
if len(compact(result)) > max_chars:
file = response_dir / (uuid4().hex + '.json')
try:
private_write(file, raw)
except (OSError, subprocess.SubprocessError, ClientError):
raise ClientError('已收到服务端响应,但完整响应保存失败;请按 traceId 核对结果,不要重复写入。',
**{key: response[key] for key in ('httpStatus', 'code', 'traceId')}) from None
del result['body']
result.update(truncated=True, responseFile=str(file), preview='')
low, high = 0, min(len(raw), max_chars)
while low < high:
middle = (low + high + 1) // 2
result['preview'] = raw[:middle]
if len(compact(result)) <= max_chars:
low = middle
else:
high = middle - 1
result['preview'] = raw[:low]
return result
def add_arguments(parser):
parser.add_argument('action', choices=('login', 'request', 'upload', 'download'))
parser.add_argument('--base-url', help='仅登录使用;GYSmart 默认 https://am.gysmart.shop,Shop/Media 默认 https://api.zhecent.com')
parser.add_argument('--app', required=True, choices=tuple(transport.DEFAULT_BASE_URLS))
parser.add_argument('--path')
parser.add_argument('--file', help='上传的本机文件')
parser.add_argument('--output', help='下载目标文件,拒绝覆盖')
body = parser.add_mutually_exclusive_group()
body.add_argument('--body')
body.add_argument('--body-file')
parser.add_argument('--method', default='POST', choices=('GET', 'POST', 'PUT', 'PATCH', 'DELETE'))
parser.add_argument('--env-file')
parser.add_argument('--max-chars', type=int, default=6000)
parser.add_argument('--timeout', type=int, default=30)
def run(args, parser, response_dir):
if not 1024 <= args.max_chars <= 1000000 or not 1 <= args.timeout <= 120:
parser.error('max-chars 范围为 1024—1000000,timeout 范围为 1—120 秒。')
if args.action == 'login' and (args.path or args.body is not None or args.body_file):
parser.error('login 不接受业务路径或正文。')
if args.action != 'login' and (not args.path or args.base_url):
parser.error('request 需要 --path;服务地址来自已登录会话。')
if args.action == 'upload' and not args.file:
parser.error('upload 需要 --file。')
if args.action == 'download' and not args.output:
parser.error('download 需要 --output。')
if args.action != 'upload' and args.file:
parser.error('--file 仅供 upload 使用。')
if args.action != 'download' and args.output:
parser.error('--output 仅供 download 使用。')
client = RawClient(args, response_dir)
try:
result = client.login(args.base_url) if args.action == 'login' else client.request()
except ClientError as error:
result = {'ok': False, 'message': str(error), **error.details}
except (OSError, subprocess.SubprocessError, UnicodeError, EOFError, ValueError):
result = {'ok': False, 'message': '本机文件、权限或会话数据处理失败;若请求已发出,先核对结果,不要盲目重试。'}
except KeyboardInterrupt:
result = {'ok': False, 'message': '操作已取消;若请求已经发出,先核对业务结果。'}
print(client.redact(compact(result)))
return 0 if result['ok'] else 1
+82
View File
@@ -0,0 +1,82 @@
import argparse
from pathlib import Path
import subprocess
import sys
from . import api, media, media_commands, system_commands
from .system_client import SystemClient
from .transport import Client, ClientError, compact
def default_session(app):
cwd = Path.cwd()
for parent in (cwd, *cwd.parents):
if (parent / "scripts" / "lightcore_api.py").is_file():
return parent / ".work" / "lightcore-api" / app / ".env"
if (parent / "业务" / "README.md").is_file() and (parent / "工具" / "README.md").is_file():
sibling = parent.parent / "LightCore"
if (sibling / "scripts" / "lightcore_api.py").is_file():
return sibling / ".work" / "lightcore-api" / app / ".env"
return Path.home() / ".lightcore" / "lightcore-api" / app / ".env"
def login(client, args):
return client.login(args.base_url)
def preview_size(value):
size = int(value)
if not 1024 <= size <= 1000000:
raise argparse.ArgumentTypeError("预览长度范围为 1024–1000000")
return size
def app_options(parser, app):
parser.set_defaults(app=app)
parser.add_argument("--env-file", type=Path, help="本机会话文件路径")
parser.add_argument("--timeout", type=int, choices=range(1, 121), metavar="秒",
default=30, help="HTTP 超时,1–120 秒,默认 30")
parser.add_argument("--max-chars", type=preview_size, metavar="字符",
default=6000, help="业务响应预览上限,默认 6000")
return parser.add_subparsers(required=True)
def parser():
root = argparse.ArgumentParser(prog="lightcore", description="LightCore 应用命令行工具")
apps = root.add_subparsers(dest="command", required=True)
raw = apps.add_parser("api", help="调用应用后台接口,支持登录、JSON、上传和下载")
api.add_arguments(raw)
raw.set_defaults(api_parser=raw)
app = apps.add_parser("media", help="Media 后台操作")
commands = app_options(app, "media")
auth = commands.add_parser("login", help="交互登录并保存本机 Media 会话",
description="执行 lightcore media login 后输入后台账号和密码。")
auth.add_argument("--base-url", help="Media 服务地址,默认 https://api.zhecent.com")
auth.set_defaults(handler=login, endpoint="/auth/login")
media_commands.add_commands(commands, media.add_file_commands(commands))
system = apps.add_parser("system", help="System 后台操作")
system_commands.add_commands(app_options(system, "system"))
return root
def main(argv=None):
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
stream.reconfigure(encoding="utf-8")
args = parser().parse_args(argv)
if args.env_file is None:
args.env_file = default_session(args.app)
if args.command == "api":
return api.run(args, args.api_parser, Path.cwd() / ".work" / "lightcore" / args.app)
client = (SystemClient(args.env_file, args.timeout) if args.app == "system"
else Client(args.app, args.env_file, args.timeout))
try:
result = args.handler(client, args)
except ClientError as error:
result = {"ok": False, "message": str(error), **error.details}
except (OSError, ValueError, EOFError, subprocess.SubprocessError):
result = {"ok": False, "message": "无法读取会话或处理本机文件,请核对路径和权限。"}
except KeyboardInterrupt:
result = {"ok": False, "message": "操作已取消。"}
print(client.redact(compact(result)))
return 0 if result["ok"] else 1
+136
View File
@@ -0,0 +1,136 @@
import argparse
from pathlib import Path
import re
from uuid import UUID, uuid4
from .transport import ClientError, MultipartBody, compact
DOCUMENT = "/content/document/"
def positive_int(value):
parsed = int(value)
if parsed <= 0:
raise argparse.ArgumentTypeError("需要正整数")
return parsed
def checked_result(client, response):
if response.get("downloaded"):
return response
payload = response["json"]
if client.success(response) and isinstance(payload.get("data"), dict):
return payload["data"]
message = ""
if isinstance(payload, dict):
message = payload.get("msg") or payload.get("message") or ""
raise ClientError(
message[:240] if isinstance(message, str) and message else "Media 未返回预期结果。",
**{key: response[key] for key in ("httpStatus", "code", "traceId") if response[key] is not None},
)
def request(client, path, fields):
return checked_result(client, client.exchange(path, compact(fields).encode("utf-8")))
def find(client, args):
data = request(client, DOCUMENT + "getDocumentList", {
"keyword": args.keyword, "pageNo": args.page, "pageSize": args.limit,
})
return {"ok": True, "total": data["total"], "page": args.page, "items": [
{"documentId": item["id"], "title": item["title"]} for item in data.get("list") or []
]}
def document_files(client, document_id):
data = request(client, DOCUMENT + "getDocumentDetail", {"documentId": document_id})
return [
{"fileId": item["id"], "fileName": item["fileName"],
"mimeType": item["mimeType"], "bytes": item["fileSize"]}
for item in data.get("files") or []
]
def list_files(client, args):
return {"ok": True, "documentId": args.document_id,
"items": document_files(client, args.document_id)}
def upload(client, args):
request_id = str(args.request_id or uuid4())
fields = {"requestId": request_id}
if args.category:
fields["category"] = args.category
try:
payload = MultipartBody(args.file, fields)
response = client.exchange("/content/social/uploadAsset", payload)
file = checked_result(client, response)
if type(file.get("id")) is not int or file["id"] <= 0:
raise ClientError("Media 上传回执缺少有效文件 ID。")
except ClientError as error:
raise ClientError(str(error), **error.details, requestId=request_id) from None
return {"ok": True, "fileId": file["id"]}
def local_name(file):
name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", file["fileName"]).strip(" .")
return f'{file["fileId"]}-{name or "attachment"}'
def get_files(client, args):
files = {file["fileId"]: file for file in document_files(client, args.document_id)}
directory = args.output_dir or Path(".work", "media", str(args.document_id))
items = []
for file_id in dict.fromkeys(args.file_id):
file = files.get(file_id)
if file is None:
items.append({"ok": False, "fileId": file_id, "message": "文件不属于当前文档。"})
continue
try:
fields = {"documentId": args.document_id, "fileId": file_id}
result = client.exchange(
DOCUMENT + "downloadAsset", compact(fields).encode("utf-8"),
output=directory / local_name(file),
)
if not result.get("downloaded"):
checked_result(client, result)
raise ClientError("Media 响应未包含可下载的文件。")
except ClientError as error:
items.append({"ok": False, "fileId": file_id, "message": str(error), **error.details})
else:
items.append({"ok": True, "fileId": file_id,
"outputFile": result["outputFile"], "bytes": result["bytes"]})
return {"ok": all(item["ok"] for item in items), "items": items}
def add_file_commands(commands):
files = commands.add_parser("files", help="查找资料、列出附件、上传或下载文件")
actions = files.add_subparsers(required=True)
search = actions.add_parser("find", help="按关键词查找 Media 资料文档",
description='示例 lightcore media files find --keyword "推窗器"。返回文档 ID 和标题。')
search.add_argument("--keyword", required=True, help="文档标题或正文关键词")
search.add_argument("--page", type=positive_int, default=1, help="页码,默认 1")
search.add_argument("--limit", type=int, choices=range(1, 101), metavar="条数",
default=10, help="每页 1–100 条,默认 10")
search.set_defaults(handler=find, endpoint=DOCUMENT + "getDocumentList")
listing = actions.add_parser("list", help="查看文档的附件清单",
description="示例 lightcore media files list --document-id 58。返回文件 ID、名称、类型和大小。")
listing.add_argument("--document-id", type=positive_int, required=True)
listing.set_defaults(handler=list_files, endpoint=DOCUMENT + "getDocumentDetail")
sending = actions.add_parser("upload", help="上传一个本地文件到 Media",
description='示例 lightcore media files upload "推窗器说明书.pdf"。返回 fileId。')
sending.add_argument("file", type=Path, help="文件路径")
sending.add_argument("--category", help="可选的 Media 文件分类")
sending.add_argument("--request-id", type=UUID, help="核对结果后重试时复用的上传 UUID")
sending.set_defaults(handler=upload, endpoint="/content/social/uploadAsset")
download = actions.add_parser("get", help="从文档下载指定附件",
description="示例 lightcore media files get --document-id 58 --file-id 123。返回本地路径和字节数。")
download.add_argument("--document-id", type=positive_int, required=True)
download.add_argument("--file-id", type=positive_int, action="append", required=True, help="附件 ID,可重复指定")
download.add_argument("--output-dir", type=Path, help="保存目录,默认 .work/media/<文档 ID>")
download.set_defaults(handler=get_files, endpoint=DOCUMENT + "downloadAsset")
return actions
+212
View File
@@ -0,0 +1,212 @@
import argparse
import json
from pathlib import Path
import re
from .api import format_response
from .media import positive_int
from .media_schema import CASES, DESCRIPTIONS, enum_for, example_body, request_schema
from .transport import ClientError, compact, reject_constant
SOCIAL = "/content/social"
SCRIPT = "/content/script"
DOCUMENT = "/content/document"
PAGINATION = "pageNo pageSize"
SCRIPT_DELETE = "requestId id expectedUpdatedAt"
# Each entry declares the existing backend path and the input shown in --help.
GROUPS = {
"auth": ("个人资料与会话", "/auth", [
("info", "info", "查看当前管理员身份", ""),
("update-profile", "updateProfile", "修改当前管理员显示名", "displayName*"),
("change-password", "changePassword", "修改当前管理员密码", "oldPassword newPassword", "private"),
]),
"admin-accounts": ("Media 后台管理员", "/account", [
("list", "getList", "查询后台管理员", f"{PAGINATION} keyword role status"),
("create", "create", "创建后台管理员", "username password displayName", "private"),
("update-status", "updateStatus", "设置管理员状态为 enabled 或 disabled", "id* status*"),
("reset-password", "resetPassword", "重置管理员密码", "id password", "private"),
("delete", "delete", "删除后台管理员", "id*"),
]),
"accounts": ("社媒账号", SOCIAL, [
("list", "getAccountList", "查询社媒账号", f"{PAGINATION} keyword platform isValid"),
("get", "getAccountDetail", "查看社媒账号详情", "accountKey*"),
("save", "saveAccount", "新建或更新社媒账号",
"requestId accountKey platform brandName accountName accountHandle agentGuideMarkdown isValid validityNote expectedUpdatedAt", "json"),
("set-validity", "setAccountValidity", "设置社媒账号有效状态",
"accountKey requestId isValid validityNote expectedUpdatedAt", "json"),
]),
"contents": ("正式稿件", SOCIAL, [
("list", "getContentList", "查询正式稿件", f"{PAGINATION} keyword contentType"),
("get", "getContentDetail", "查看稿件正文、附件和发布记录", "contentId*"),
("save", "saveContent", "新建或更新正式稿件",
"requestId contentId contentType title body contentFormat coverFileIds mediaFileIds "
"creationNotes researchFacts researchSources imageDetails expectedUpdatedAt", "json"),
("save-image-detail", "saveImageDetail", "保存一张稿件图片的创作资料",
"contentId requestId expectedUpdatedAt fileId text prompt referenceFileIds notes", "json"),
("download", "downloadAsset", "下载与稿件关联的文件", "contentId* fileId*", "download"),
]),
"references": ("参考内容", SOCIAL, [
("list", "getReferenceList", "查询参考内容", f"{PAGINATION} keyword platform contentType"),
("get", "getReferenceDetail", "查看参考内容详情", "referenceId*"),
("save", "saveReference", "新建或更新参考内容",
"requestId referenceId platform contentType creatorName creatorHandle creatorProfileUrl "
"sourceContentUrl title bodyMarkdown coverFileIds mediaFileIds expectedUpdatedAt", "json"),
("delete", "deleteReference", "删除参考内容记录", "referenceId requestId expectedUpdatedAt", "json"),
("download", "downloadReferenceAsset", "下载与参考内容关联的文件", "referenceId* fileId*", "download"),
]),
"publications": ("人工发布记录", SOCIAL, [
("list", "getPublicationList", "查询已登记的发布记录", f"{PAGINATION} contentId accountKey"),
("mark", "markPublication", "登记已经人工完成的平台发布",
"requestId contentId accountKey publishedAt publicUrl", "json"),
]),
"documents": ("通用文档和产品资料", DOCUMENT, [
("list", "getDocumentList", "查询文档", f"{PAGINATION} keyword excludeKeyword searchScope matchMode projectId"),
("get", "getDocumentDetail", "读取文档正文和附件", "documentId*"),
("save", "saveDocument", "新建或更新文档以及附件关联",
"requestId documentId expectedUpdatedAt title bodyMarkdown fileIds", "json"),
("delete", "deleteDocument", "删除文档记录", "documentId requestId expectedUpdatedAt", "json"),
]),
"projects": ("短剧项目", SCRIPT, [
("list", "getProjectList", "查询短剧项目", f"{PAGINATION} keyword"),
("get", "getProjectDetail", "查看项目详情与文档关联", "projectId*"),
("context", "getCreationContext", "读取项目必读正文及参考文档清单", "projectId*"),
("save", "saveProject", "新建或更新短剧项目", "requestId projectId expectedUpdatedAt name description documents", "json"),
("delete", "deleteProject", "删除项目", SCRIPT_DELETE, "json"),
]),
"episodes": ("短剧分集", SCRIPT, [
("list", "getEpisodeList", "查询项目的分集", f"{PAGINATION} projectId* keyword"),
("get", "getEpisodeDetail", "查看分集详情", "episodeId*"),
("save", "saveEpisode", "新建或更新分集", "requestId episodeId expectedUpdatedAt projectId name sortOrder", "json"),
("delete", "deleteEpisode", "删除分集", SCRIPT_DELETE, "json"),
]),
"resources": ("角色、场景和道具", SCRIPT, [
("list", "getResourceList", "按项目查询资源", f"{PAGINATION} projectId* keyword type"),
("get", "getResourceDetail", "查看资源详情", "resourceId*"),
("save", "saveResource", "新建或更新资源", "requestId resourceId expectedUpdatedAt projectId name type prompt imageFileIds", "json"),
("delete", "deleteResource", "删除资源", SCRIPT_DELETE, "json"),
("download", "downloadResourceImage", "下载与资源关联的图片", "resourceId* fileId*", "download"),
]),
"videos": ("短剧视频与参考图", SCRIPT, [
("list", "getVideoList", "查询分集的视频", f"{PAGINATION} episodeId* keyword"),
("get", "getVideoDetail", "查看视频正文和参考图", "videoId*"),
("save", "saveVideo", "新建或更新视频",
"requestId videoId expectedUpdatedAt projectId episodeId name sortOrder mode durationSeconds "
"characterResourceIds sceneResourceIds propResourceIds style context body dialogue audioRequirements "
"visualRequirements staffNotes referenceImages", "json"),
("delete", "deleteVideo", "删除视频", SCRIPT_DELETE, "json"),
("prompt", "getVideoPrompt", "读取视频生成提示词和输入图", "videoId*"),
("image-prompt", "getReferenceImagePrompt", "读取指定参考图的生成提示词", "videoId* key*"),
("download", "downloadReferenceImage", "下载与视频关联的图片", "videoId* fileId*", "download"),
]),
"storage": ("Media 存储绑定", "/storage", [
("get", "getConfig", "查看 Media 存储配置", ""),
("save", "saveConfig", "保存 Media 存储配置", "bucket clientSecret", "private"),
]),
}
def parse_bool(value):
values = {"true": True, "false": False}
if value not in values:
raise ValueError("需要 true 或 false")
return values[value]
def page_size(value):
parsed = positive_int(value)
if parsed > 100:
raise ValueError("每页最多 100 条")
return parsed
def add_field(parser, endpoint, spec):
field = spec.removesuffix("*")
flag = "--" + re.sub(r"[A-Z]", lambda hit: "-" + hit[0].lower(), field)
description = DESCRIPTIONS.get(field, f"JSON 字段 {field}")
values = enum_for(endpoint, field)
if values:
description += ",可选 " + " / ".join(values)
options = {"dest": field, "required": spec.endswith("*"), "help": description}
if field in ("pageNo", "pageSize"):
options["type"] = positive_int if field == "pageNo" else page_size
options["default"] = 1 if field == "pageNo" else 20
options["help"] += f",默认 {options['default']}"
elif field == "isValid":
options.update(type=parse_bool, metavar="true|false")
elif field == "id" or field.endswith("Id"):
options["type"] = positive_int
parser.add_argument(flag, **options)
return field
class ShowRequest(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
endpoint, fields = namespace.request_spec
schema = request_schema(endpoint, fields)
result = schema if option_string == "--schema" else example_body(endpoint, schema, values or "create")
print(json.dumps(result, ensure_ascii=False, indent=2))
parser.exit()
def read_body(args):
if not (args.body_file or args.body is not None):
return {field: getattr(args, field) for field in args.fields if getattr(args, field) is not None}
text = args.body_file.read_text(encoding="utf-8-sig") if args.body_file else args.body
try:
data = json.loads(text, parse_constant=reject_constant)
except (ValueError, UnicodeError):
raise ClientError("请求正文必须是有效 JSON 对象。") from None
if not isinstance(data, dict):
raise ClientError("请求正文必须是 JSON 对象。")
return data
def call(client, args):
body = read_body(args)
client.remember_secrets(body)
response = client.exchange(args.endpoint, compact(body).encode("utf-8"), output=args.output)
if args.output is not None and client.success(response) and not response.get("downloaded"):
raise ClientError("Media 响应未包含可下载的文件。", traceId=response.get("traceId"))
return format_response(client, response, Path.cwd() / ".work" / "lightcore" / "media", args.max_chars)
def add_operation(actions, prefix, name, endpoint, summary, fields, mode="fields"):
command = actions.add_parser(name, help=summary, description=summary, allow_abbrev=False)
command.set_defaults(handler=call, endpoint=prefix + "/" + endpoint, body=None, body_file=None, output=None)
if mode in ("json", "private"):
command.set_defaults(request_spec=(endpoint, fields.split()))
input_group = command.add_mutually_exclusive_group(required=True)
input_group.add_argument("--schema", action=ShowRequest, nargs=0,
help="离线查看 JSON 字段类型、必填条件和嵌套结构")
if endpoint in CASES:
input_group.add_argument("--example", action=ShowRequest, nargs="?", const="create",
choices=("create", "update"), help="离线生成示例 JSON,默认 create,更新用 update")
else:
input_group.add_argument("--example", action=ShowRequest, nargs=0, help="离线生成示例 JSON")
if mode == "private":
input_group.add_argument("--body-file", type=Path, help="本机私有 JSON 输入文件")
else:
input_group.add_argument("--body", help="JSON 对象")
input_group.add_argument("--body-file", type=Path, help="UTF-8 JSON 文件")
else:
command.set_defaults(fields=[add_field(command, endpoint, field) for field in fields.split()])
if mode == "download":
command.add_argument("--output", type=Path, required=True, help="保存路径,拒绝覆盖")
def add_commands(commands, file_actions):
for group, (description, prefix, operations) in GROUPS.items():
group_parser = commands.add_parser(group, help=description, description=description)
actions = group_parser.add_subparsers(required=True)
if group == "auth":
for name, handler, help_text in [
("refresh", lambda client, _: client.refresh(), "刷新本机 Media 会话"),
("logout", lambda client, _: client.logout(), "在服务端退出并清理本机 Token"),
]:
actions.add_parser(name, help=help_text, description=help_text).set_defaults(
handler=handler, endpoint=prefix + "/" + name,
)
for operation in operations:
add_operation(actions, prefix, *operation)
add_operation(file_actions, SOCIAL, "search", "getFileList", "按文件名查找素材台账", f"{PAGINATION} keyword type")
+262
View File
@@ -0,0 +1,262 @@
"""Request descriptions shared by Media help, schemas and examples."""
from uuid import uuid4
ENUMS = {
"platform": ("xiaohongshu", "douyin", "wechat_video", "bilibili"),
"contentType": ("image_text", "video"),
"contentFormat": ("plain_text", "html"),
"searchScope": ("all", "title", "body"),
"matchMode": ("all", "any"),
"role": ("owner", "admin"),
"status": ("enabled", "disabled"),
"mode": ("omni_reference", "first_last_frame"),
"frameRole": ("reference", "first", "last"),
}
RESOURCE_TYPES = ("character", "scene", "prop")
FILE_TYPES = ("image", "video", "document", "audio", "archive", "other")
DESCRIPTIONS = {
"requestId": "本次写入的 UUID。核实后重试同一输入时复用原值。",
"expectedUpdatedAt": "刚从详情读取的 updatedAt,保留原有时间精度。",
"publishedAt": "人工发布的实际时间,使用带时区的 RFC3339。",
"pageNo": "页码,从 1 开始",
"pageSize": "每页条数,范围 1–100",
"keyword": "搜索关键词",
"excludeKeyword": "排除关键词,多个词用空格分隔",
"searchScope": "搜索范围,all 为标题和正文,默认 all",
"matchMode": "多词匹配方式,all 为全部命中,默认 all",
"isValid": "社媒账号是否有效",
"bodyMarkdown": "Markdown 正文。",
"durationSeconds": "生成时长,1–3600 秒,新建默认 10 秒。",
"referenceImages": "参考图数组。修改时提交希望保留的完整数组。",
"mode": "视频制作模式。first_last_frame 要求参考图中各有一项 first 和 last。",
"frameRole": "参考图用途,省略时为 reference。",
"fileIds": "有序的 Media 文件 ID 数组。",
"imageDetails": "按稿件图片记录文案和提示词。fileId 必须属于当前稿件的封面、正文素材列表或正文引用。",
"researchFacts": "已核验事实,可引用 researchSources 中的 key。",
"researchSources": "稿件来源条目。",
"sourceKeys": "对应当前稿件 researchSources 内的 key。",
"documents": "项目文档关联数组。required 指定是否为本项目必读。",
"clientSecret": "Media 存储客户端密钥,使用私有输入文件。",
}
ARRAY_OBJECTS = {
"referenceImages": ("key name purpose prompt resourceIds referenceFileIds fileId frameRole", "name"),
"documents": ("documentId required", "documentId"),
"imageDetails": ("fileId text prompt referenceFileIds notes", "fileId"),
"researchFacts": ("text scope sourceKeys verifiedAt", "text"),
"researchSources": ("key title url fileIds notes", "key title"),
}
# New and existing records share a backend DTO. The rules below describe the
# conditions enforced by the application service and used by the examples.
CASES = {
"saveAccount": {
"create": "requestId accountKey platform accountName isValid",
"update": "requestId accountKey platform accountName isValid expectedUpdatedAt",
},
"saveContent": {"create": "requestId contentType title", "update": "requestId contentId expectedUpdatedAt"},
"saveReference": {
"create": "requestId platform contentType creatorName title",
"update": "requestId referenceId platform contentType creatorName title expectedUpdatedAt",
},
"saveDocument": {"create": "requestId title", "update": "requestId documentId expectedUpdatedAt"},
"saveProject": {"create": "requestId name", "update": "requestId projectId expectedUpdatedAt"},
"saveEpisode": {"create": "requestId projectId name", "update": "requestId episodeId expectedUpdatedAt"},
"saveResource": {"create": "requestId projectId name type", "update": "requestId resourceId expectedUpdatedAt"},
"saveVideo": {"create": "requestId episodeId name", "update": "requestId videoId expectedUpdatedAt"},
}
REQUIRED = {
"changePassword": "oldPassword newPassword",
"create": "username password displayName",
"resetPassword": "id password",
"setAccountValidity": "accountKey requestId isValid expectedUpdatedAt",
"saveImageDetail": "contentId requestId expectedUpdatedAt fileId",
"deleteReference": "referenceId requestId expectedUpdatedAt",
"markPublication": "requestId contentId accountKey publishedAt",
"deleteDocument": "documentId requestId expectedUpdatedAt",
"deleteProject": "requestId id expectedUpdatedAt",
"deleteEpisode": "requestId id expectedUpdatedAt",
"deleteResource": "requestId id expectedUpdatedAt",
"deleteVideo": "requestId id expectedUpdatedAt",
"saveConfig": "bucket clientSecret",
}
EXAMPLE_FIELDS = {
"saveAccount": "brandName",
"saveContent": "title body contentFormat mediaFileIds researchSources researchFacts imageDetails",
"saveReference": "title bodyMarkdown",
"saveDocument": "title bodyMarkdown fileIds",
"saveProject": "name description documents",
"saveEpisode": "name sortOrder",
"saveResource": "name imageFileIds",
"saveVideo": "name mode durationSeconds body referenceImages",
"saveImageDetail": "text prompt referenceFileIds",
}
UPDATE_EXAMPLE_FIELDS = {
"saveAccount": "validityNote",
"saveContent": "title",
"saveReference": "bodyMarkdown",
"saveDocument": "bodyMarkdown",
"saveProject": "description",
"saveEpisode": "sortOrder",
"saveResource": "prompt",
"saveVideo": "body",
}
SAMPLE_VALUES = {
"accountKey": "example-media-account",
"username": "example-admin",
"bodyMarkdown": "示例正文",
"bucket": "media",
"contentId": 58,
"documentId": 7,
"episodeId": 3,
"expectedUpdatedAt": "2026-01-01T00:00:00Z",
"fileId": 123,
"frameRole": "reference",
"key": "example-source",
"publishedAt": "2026-01-01T12:00:00+08:00",
"sourceKeys": ["example-source"],
"resourceIds": [],
"referenceFileIds": [],
"verifiedAt": "2026-01-01",
"durationSeconds": 10,
"mode": "omni_reference",
"password": "REPLACE_WITH_PASSWORD",
"oldPassword": "REPLACE_WITH_OLD_PASSWORD",
"newPassword": "REPLACE_WITH_NEW_PASSWORD",
"clientSecret": "REPLACE_WITH_CLIENT_SECRET",
}
def enum_for(endpoint, field):
if field == "type":
if endpoint in ("getResourceList", "saveResource"):
return RESOURCE_TYPES
if endpoint == "getFileList":
return FILE_TYPES
return ENUMS.get(field)
def field_schema(endpoint, field):
values = enum_for(endpoint, field)
if values:
result = {"type": "string", "enum": list(values)}
elif field in ARRAY_OBJECTS:
fields, required = ARRAY_OBJECTS[field]
items = object_schema(endpoint, fields.split(), required.split())
if field == "referenceImages":
items["properties"]["key"].update(format="uuid", description="参考图 UUID,新增时可省略,编辑已有参考图时保留原值。")
items["properties"]["fileId"]["minimum"] = 0
result = {"type": "array", "items": items}
elif field.endswith("Ids"):
result = {"type": "array", "items": {"type": "integer", "minimum": 1}}
elif field == "sourceKeys":
result = {"type": "array", "items": {"type": "string"}}
elif field in ("required", "isValid"):
result = {"type": "boolean"}
elif field in ("id", "pageNo", "pageSize", "sortOrder", "durationSeconds") or field.endswith("Id") and field != "requestId":
result = {"type": "integer"}
if field == "pageSize":
result.update(minimum=1, maximum=100, default=20)
elif field == "pageNo":
result.update(minimum=1, default=1)
elif field == "durationSeconds":
result.update(minimum=1, maximum=3600, default=10)
else:
result["minimum"] = 0 if field == "sortOrder" else 1
else:
result = {"type": "string"}
if field in ("expectedUpdatedAt", "publishedAt"):
result["format"] = "date-time"
elif field == "verifiedAt":
result["format"] = "date"
elif field == "requestId":
result["format"] = "uuid"
elif field in ("password", "oldPassword", "newPassword", "clientSecret"):
result["writeOnly"] = True
if field in DESCRIPTIONS:
result["description"] = DESCRIPTIONS[field]
if field == "name" or field == "title":
result.update(minLength=1, maxLength=240)
if field in ("accountKey", "accountName", "creatorName"):
result.update(minLength=1, maxLength=160)
if field in ("username", "displayName"):
result.update(minLength=3 if field == "username" else 1, maxLength=50)
if field in ("newPassword", "password"):
result["minLength"] = 8
return result
def object_schema(endpoint, fields, required):
return {
"type": "object",
"properties": {field: field_schema(endpoint, field) for field in fields},
"required": required,
}
def request_schema(endpoint, fields):
names = [field.removesuffix("*") for field in fields]
required = REQUIRED.get(endpoint)
result = object_schema(endpoint, names, required.split() if required else [
field[:-1] for field in fields if field.endswith("*")
])
if endpoint in CASES:
case_fields = {mode: values.split() for mode, values in CASES[endpoint].items()}
create, update = case_fields["create"], case_fields["update"]
result["required"] = [field for field in create if field in update]
if endpoint == "saveAccount":
result["description"] = "服务端通过 accountKey 查找账号。更新时传 expectedUpdatedAt,同时提交希望保留的账号资料。"
else:
selector = update[1]
result["properties"][selector].update(minimum=0, description="省略或填 0 表示新建,正整数表示更新。")
result["if"] = {"required": [selector], "properties": {selector: {"minimum": 1}}}
result["then"] = {"required": update}
result["else"] = {"required": create}
if endpoint == "saveReference":
result["description"] = "更新时提交希望保留的完整参考内容和附件字段。"
else:
result["description"] = "更新时省略不打算修改的字段。传入的数组按整组保存。"
result["x-required-by-operation"] = case_fields
return result
def example_value(name, schema):
if name == "requestId":
return str(uuid4())
if name in SAMPLE_VALUES:
return SAMPLE_VALUES[name]
if "enum" in schema:
return schema["enum"][0]
if schema["type"] == "object":
is_reference_image = "frameRole" in schema["properties"]
sample = {}
for field, spec in schema["properties"].items():
if is_reference_image and field == "key":
continue
sample[field] = example_value(field, spec)
if is_reference_image:
sample["fileId"] = 0
return sample
if schema["type"] == "array":
return [example_value(name, schema["items"])]
if schema["type"] == "integer":
return 123 if name.endswith("Ids") else 1
if schema["type"] == "boolean":
return True
if name == "url":
return "https://example.com/source"
return "示例"
def example_body(endpoint, schema, mode):
required = schema.get("x-required-by-operation", {}).get(mode, schema["required"])
example_fields = UPDATE_EXAMPLE_FIELDS if mode == "update" else EXAMPLE_FIELDS
fields = dict.fromkeys((*required, *example_fields.get(endpoint, "").split()))
return {field: example_value(field, schema["properties"][field]) for field in fields}
+65
View File
@@ -0,0 +1,65 @@
"""System Admin authentication over the shared HTTP transport."""
import base64
import getpass
import json
import time
from .transport import KEYS, SECRET_FIELDS, Client, ClientError, base_url, compact, session_lock
LOGIN_PATH = "/login/account"
LOGOUT_PATH = "/login/outLogin"
class SystemClient(Client):
secret_fields = SECRET_FIELDS | {"secretkey", "accesskey", "accesskeyid", "accesskeysecret"}
def __init__(self, env_file, timeout):
super().__init__("system", env_file, timeout)
def configured_base(self, settings, explicit=None):
address = explicit or settings.get(KEYS[0])
if not address or not address.strip():
raise ClientError("首次登录 System 请通过 --base-url 指定目标后端地址。")
return base_url(address, self.app)
def login(self, explicit_base=None):
address = self.login_base(explicit_base)
username = input("System 管理员账号: ")
password = getpass.getpass("System 管理员密码: ")
self.secrets.append(password)
payload = compact({"username": username, "password": password, "type": "account"}).encode("utf-8")
response = self.send(address, LOGIN_PATH, payload)
details = {key: response[key] for key in ("httpStatus", "code", "traceId")}
data = (response["json"] or {}).get("data") if self.success(response) else None
if not isinstance(data, dict) or data.get("status") != "ok":
raise ClientError("System 登录失败,请核对实例与管理员账号。", **details)
token = data.get("token")
if not isinstance(token, str) or not token:
raise ClientError("System 登录响应缺少 Token。", **details)
self.secrets.append(token)
try:
_, encoded, _ = token.split(".")
encoded += "=" * (-len(encoded) % 4)
claims = json.loads(base64.b64decode(encoded, altchars=b"-_", validate=True))
expires_at = claims.get("exp") if isinstance(claims, dict) else None
except ValueError:
expires_at = None
if type(expires_at) is not int or expires_at <= time.time():
raise ClientError("System 登录响应的 Token 到期时间无效。", **details)
with session_lock(self.env, self.timeout):
self.login_base(address)
self.write_session({KEYS[0]: address, KEYS[1]: token, KEYS[3]: str(expires_at)})
return {"ok": True, **details, "message": "已保存本机 System 会话。"}
def logout(self):
with session_lock(self.env, self.timeout):
session = self.read_session()
response = self.send(session[KEYS[0]], LOGOUT_PATH, b"{}", session[KEYS[1]])
details = {key: response[key] for key in ("httpStatus", "code", "traceId")}
if not self.success(response):
raise ClientError("System 退出失败,本机会话文件尚未更新。", **details)
self.clear_session(details)
return {"ok": True, **details}
+167
View File
@@ -0,0 +1,167 @@
"""CLI entry points for the System Admin HTTP API."""
import argparse
import json
from pathlib import Path
import re
import subprocess
from .api import format_response
from .system_client import LOGIN_PATH, LOGOUT_PATH
from .system_routes import GROUPS
from .system_schema import REQUESTS
from .transport import ClientError, MultipartBody, compact, private_output, reject_constant
PRIVATE_INPUT_FIELDS = {"accessKey", "accessKeyId", "accessKeySecret", "secretKey", "oldPassword", "newPassword"}
def example_value(name, field):
if "const" in field:
return field["const"]
if "default" in field:
return field["default"]
if "examples" in field:
return field["examples"][0]
if "enum" in field:
return field["enum"][0]
if field["type"] == "array":
return [example_value(name, field["items"])]
if field["type"] == "object":
return {key: example_value(key, spec) for key, spec in field["properties"].items()}
if field["type"] == "integer":
return 600 if name == "ttl" else field.get("minimum", 1)
if field["type"] == "boolean":
return True
examples = {"uuid": "0198d956-1111-4444-8888-111111111111", "uri": "https://example.com/",
"email": "admin@example.com", "binary": "example.png"}
if field.get("format") in examples:
return examples[field["format"]]
return {"rr": "www", "value": "192.0.2.1", "domains": "example.com",
"domainName": "example.com", "modules": "system", "tables": "system_admin_users"}.get(name, "示例")
class ShowRequest(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
schema = namespace.request_schema
result = schema
if option_string == "--example":
result = {name: example_value(name, field) for name, field in schema["properties"].items()
if name in schema["required"] or "default" in field or "examples" in field}
print(json.dumps(result, ensure_ascii=False, indent=2))
parser.exit()
def request_body(args):
flags = {name: getattr(args, name) for name in args.fields if getattr(args, name) is not None}
if args.body_file is None:
return {name: field["default"] for name, field in args.request_schema["properties"].items()
if "default" in field and args.mode != "upload"} | flags
if flags:
raise ClientError("--body-file 与字段参数只能选择一种。")
try:
body = json.loads(args.body_file.read_text(encoding="utf-8-sig"), parse_constant=reject_constant)
except ValueError:
raise ClientError("请求正文必须是有效 JSON 对象。") from None
if not isinstance(body, dict):
raise ClientError("请求正文必须是 JSON 对象。")
return body
def save_private_json(args, data, details):
target = args.output.absolute()
try:
with private_output(target) as stream:
stream.write((compact(data) + "\n").encode("utf-8"))
except (OSError, subprocess.SubprocessError, ClientError):
raise ClientError("已收到服务端响应,但私有输出保存失败。", **details) from None
return {"ok": True, **details, "outputFile": str(target)}
def call(client, args):
if args.output is not None and (args.output.exists() or args.output.is_symlink()):
raise ClientError("目标文件已存在,拒绝覆盖。")
body = request_body(args)
client.remember_secrets(body)
payload = (MultipartBody(args.file, body) if args.mode == "upload" else compact(body).encode("utf-8"))
response = client.exchange(args.endpoint, payload, output=args.output if args.mode == "zip" else None)
if response.get("downloaded"):
return response
details = {key: response[key] for key in ("httpStatus", "code", "traceId")}
if args.mode in ("zip", "private-output"):
if not client.success(response):
message = (response["json"] or {}).get("msg") if isinstance(response["json"], dict) else None
raise ClientError(message or "System 请求失败。", **details)
if args.mode == "zip":
raise ClientError("System 响应未包含证书 ZIP。", **details)
data = response["json"].get("data")
if not isinstance(data, dict) or not data:
raise ClientError("System 响应未包含所需数据。", **details)
return save_private_json(args, data, details)
if args.endpoint == "/user/updatePassword" and client.success(response):
data = response["json"].get("data")
if not isinstance(data, dict) or data.get("success") is not True:
message = (data or {}).get("message") if isinstance(data, dict) else None
raise ClientError(message or "System 密码修改失败。", **details)
return format_response(client, response, Path.cwd() / ".work" / "lightcore" / "system", args.max_chars)
def add_operation(actions, prefix, name, endpoint, summary, request_type, mode=None):
command = actions.add_parser(name, help=summary, description=summary, allow_abbrev=False)
request = REQUESTS[request_type] if request_type else {"properties": {}, "required": []}
schema = {"type": "object", **request}
private_input = bool(PRIVATE_INPUT_FIELDS.intersection(schema["properties"]))
inputs = command.add_mutually_exclusive_group(required=private_input)
inputs.add_argument("--schema", action=ShowRequest, nargs=0, help="离线查看请求字段、类型和约束")
inputs.add_argument("--example", action=ShowRequest, nargs=0, help="离线生成示例请求")
if mode == "upload":
command.add_argument("--file", type=Path, required=True, help="上传的本机文件")
else:
label = "本机私有 JSON 输入文件" if private_input else "UTF-8 JSON 请求文件"
inputs.add_argument("--body-file", type=Path, help=label)
if mode in ("zip", "private-output"):
command.add_argument("--output", type=Path, required=True, help="私有输出路径,拒绝覆盖")
fields = []
if not private_input:
for field, spec in schema["properties"].items():
value_type = spec["type"]
if isinstance(value_type, list):
value_type = value_type[0]
if field == "file" or value_type not in ("string", "integer", "boolean"):
continue
flag = "--" + re.sub(r"[A-Z]", lambda hit: "-" + hit[0].lower(), field)
label = f"JSON 字段 {field}"
if field in schema["required"] and "default" not in spec:
label += ",必填"
options = {"dest": field, "help": label}
if value_type == "integer":
options["type"] = int
if value_type == "boolean":
options.update(type=parse_bool, metavar="true|false")
if "enum" in spec:
options["choices"] = spec["enum"]
if "default" in spec:
options["help"] += f",默认 {spec['default']}"
command.add_argument(flag, **options)
fields.append(field)
command.set_defaults(handler=call, endpoint=f"{prefix}/{endpoint}" if prefix else endpoint,
mode=mode, request_schema=schema, output=None, body_file=None, fields=fields)
def parse_bool(value):
if value not in ("true", "false"):
raise argparse.ArgumentTypeError("需要 true 或 false")
return value == "true"
def add_commands(commands):
login = commands.add_parser("login", help="交互登录 System 并保存本机会话")
login.add_argument("--base-url", help="目标后端地址,首次登录必填")
login.set_defaults(handler=lambda client, args: client.login(args.base_url), endpoint=LOGIN_PATH)
logout = commands.add_parser("logout", help="在服务端退出并清理本机 Token")
logout.set_defaults(handler=lambda client, _: client.logout(), endpoint=LOGOUT_PATH)
for group, (summary, prefix, operations) in GROUPS.items():
section = commands.add_parser(group, help=summary, description=summary)
actions = section.add_subparsers(required=True)
for operation in operations:
add_operation(actions, prefix, *operation)
+123
View File
@@ -0,0 +1,123 @@
"""Named operations for the System Admin HTTP API."""
GROUPS = {
"user": ("管理员资料", "/user", [
("info", "currentUser", "查看当前管理员", None),
("change-password", "updatePassword", "修改当前管理员密码", "UpdatePasswordReq"),
]),
"monitor": ("运行监控", None, [
("server", "/serverMonitor/getInfo", "读取服务器概览", None),
("pdf-render", "/pdfRender/getStatus", "读取 PDF Render 状态", None),
]),
"operation-logs": ("操作审计", "/adminOperationLog", [
("list", "list", "查询系统操作日志", "AdminOperationLogListReq"),
("detail", "detail", "读取操作日志详情", "AdminOperationLogDetailReq"),
]),
"http-logs": ("系统 HTTP 日志", "/systemHttpLog", [
("list", "list", "查询 HTTP 日志", "SystemHttpLogListReq"),
("detail", "detail", "读取 HTTP 日志详情", "SystemHttpLogDetailReq"),
("delete", "delete", "删除单条 HTTP 日志", "SystemHttpLogDeleteReq"),
("batch-delete", "batchDelete", "删除指定的 HTTP 日志", "SystemHttpLogBatchDeleteReq"),
]),
"trace": ("请求链路", "/requestTrace", [
("list", "list", "查询请求链路", "RequestTraceListReq"),
("detail", "detail", "读取请求链路详情", "RequestTraceDetailReq"),
]),
"database": ("数据库维护", "/dbMigrate", [
("modules", "moduleList", "读取数据库模块和表清单", None),
("create-table-task", "createTableTask", "创建按表迁移任务", "CreateTableTaskReq"),
("create-module-task", "createModuleTask", "创建按模块迁移任务", "CreateModuleTaskReq"),
("create-smart-task", "createSmartTask", "创建智能迁移任务", "CreateSmartTaskReq"),
("create-field-check-task", "createFieldCheckTask", "创建字段一致性检查任务", "CreateFieldCheckTaskReq"),
("active-task", "getActiveTask", "读取当前活动任务", None),
("task-detail", "getTaskDetail", "查看任务结果与进度", "TaskDetailReq"),
("task-list", "getTaskList", "查询维护任务", "TaskListReq"),
("check-tables", "checkTables", "检查数据库表一致性", "TableCheckReq"),
]),
"dns-accounts": ("阿里云 DNS 账号", "/aliyunDnsAccount", [
("list", "getList", "查询脱敏账号", "AliyunDNSAccountListReq"),
("create", "create", "创建 DNS 账号", "AliyunDNSAccountCreateReq"),
("update", "update", "修改 DNS 账号名称", "AliyunDNSAccountUpdateReq"),
("get-credential", "getCredential", "将凭据保存到私有文件", "AliyunDNSAccountCredentialReq", "private-output"),
("replace-credential", "replaceCredential", "替换 DNS 凭据", "AliyunDNSAccountReplaceCredentialReq"),
("validate-connection", "validateConnection", "验证 DNS 账号连接", "AliyunDNSAccountValidateReq"),
("update-status", "updateStatus", "启用或停用账号", "AliyunDNSAccountStatusReq"),
("delete", "delete", "删除已停用的账号", "AliyunDNSAccountDeleteReq"),
]),
"dns-domains": ("阿里云 DNS 域名", "/aliyunDnsDomain", [
("list", "getList", "查询 DNS 域名", "AliyunDNSDomainListReq"),
("record-options", "getRecordOptions", "查询域名的记录与 TTL 选项", "AliyunDNSRecordOptionsReq"),
]),
"dns-records": ("阿里云 DNS 记录", "/aliyunDnsRecord", [
("list", "getList", "查询 DNS 解析记录", "AliyunDNSRecordListReq"),
("create", "create", "创建 DNS 记录", "AliyunDNSRecordMutationReq"),
("update", "update", "修改 DNS 记录", "AliyunDNSRecordUpdateReq"),
("update-status", "updateStatus", "启用或停用 DNS 记录", "AliyunDNSRecordStatusReq"),
("delete", "delete", "删除 DNS 记录", "AliyunDNSRecordDeleteReq"),
]),
"ssl-accounts": ("SSL 证书 ACME 账号", "/sslCertificateAccount", [
("terms", "getTerms", "查询当前 ACME 协议", "SSLCertificateAccountGetTermsReq"),
("list", "getList", "查询 ACME 账号", "SSLCertificateAccountGetListReq"),
("register", "register", "注册 ACME 账号", "SSLCertificateAccountRegisterReq"),
]),
"ssl-requests": ("SSL 证书申请", "/sslCertificateRequest", [
("list", "getList", "查询证书申请", "SSLCertificateRequestGetListReq"),
("detail", "getDetail", "查询申请状态和 DNS 验证要求", "SSLCertificateRequestIDReq"),
("create", "create", "创建证书申请", "SSLCertificateRequestCreateReq"),
("check-dns", "checkDNS", "检查 DNS 验证记录", "SSLCertificateRequestIDReq"),
("issue", "issue", "提交异步签发任务", "SSLCertificateRequestIDReq"),
("download", "download", "下载证书 ZIP 到私有文件", "SSLCertificateRequestIDReq", "zip"),
("delete", "delete", "删除证书申请", "SSLCertificateRequestDeleteReq"),
]),
"storage-origins": ("LightCore 存储源", "/lightCoreStorageOrigin", [
("list", "getList", "查询存储源", "LightCoreStorageOriginListReq"),
("options", "getOptions", "查询存储源选项", None),
("detail", "getDetail", "查看存储源详情", "LightCoreStorageOriginDetailReq"),
("create", "create", "创建存储源", "LightCoreStorageOriginCreateReq"),
("update", "update", "修改存储源与能力", "LightCoreStorageOriginUpdateReq"),
("get-credential", "getCredential", "将凭据保存到私有文件", "LightCoreStorageOriginCredentialReq", "private-output"),
("replace-credential", "replaceCredential", "替换存储源凭据", "LightCoreStorageOriginReplaceCredentialReq"),
("validate-connection", "validateConnection", "验证存储源连接", "LightCoreStorageOriginActionReq"),
("update-status", "updateStatus", "启用或停用存储源", "LightCoreStorageOriginStatusReq"),
]),
"storage-buckets": ("LightCore 逻辑 Bucket", "/lightCoreStorageBucket", [
("list", "getList", "查询逻辑 Bucket", "LightCoreStorageBucketListReq"),
("options", "getOptions", "查询逻辑 Bucket 选项", None),
("detail", "getDetail", "查看逻辑 Bucket 详情", "LightCoreStorageBucketDetailReq"),
("create", "create", "创建逻辑 Bucket", "LightCoreStorageBucketCreateReq"),
("update-status", "updateStatus", "修改 Bucket 状态", "LightCoreStorageBucketStatusReq"),
("update-route", "updateRoute", "更新 Bucket 路由", "LightCoreStorageBucketUpdateRouteReq"),
]),
"storage-clients": ("LightCore 客户端授权", "/lightCoreStorageClient", [
("list", "getList", "查询存储客户端", "LightCoreStorageClientListReq"),
("options", "getOptions", "查询客户端选项", None),
("detail", "getDetail", "查看客户端授权详情", "LightCoreStorageClientDetailReq"),
("get-secret", "getSecret", "将客户端密钥保存到私有文件", "LightCoreStorageClientSecretReq", "private-output"),
("create", "create", "创建客户端授权", "LightCoreStorageClientCreateReq"),
("update-name", "updateName", "更新客户端名称", "LightCoreStorageClientNameReq"),
("update-status", "updateStatus", "更新客户端状态", "LightCoreStorageClientStatusReq"),
("update-grants", "updateGrants", "替换客户端授权", "LightCoreStorageClientReplaceGrantsReq"),
]),
"storage-objects": ("LightCore 对象记录", "/lightCoreStorageObject", [
("list", "getList", "查询对象台账", "LightCoreStorageObjectListReq"),
("detail", "getDetail", "查看对象详情", "LightCoreStorageObjectDetailReq"),
("get-url", "getURL", "将对象访问 URL 保存到私有文件", "LightCoreStorageObjectURLReq", "private-output"),
("delete", "delete", "提交对象删除", "LightCoreStorageObjectActionReq"),
("retry-delete", "processDeleteRetry", "重试失败的对象删除", "LightCoreStorageObjectActionReq"),
]),
"files": ("System 技术文件", "/uploadFiles", [
("list", "list", "查询技术文件", "UploadFilesListReq"),
("detail", "detail", "查看技术文件详情", "UploadFilesDetailReq"),
("delete", "delete", "删除技术文件", "UploadFilesDeleteReq"),
("upload", "upload", "上传本机文件", "UploadFilesMultipart", "upload"),
("import-url", "downloadFromUrl", "从 URL 导入技术文件", "DownloadFromUrlReq"),
("rename", "renameFile", "修改文件名", "RenameFileReq"),
("move", "moveToDirectory", "移动文件到目录", "MoveToDirectoryReq"),
]),
"file-directories": ("System 技术文件目录", "/uploadFiles/directory", [
("list", "list", "查询文件目录树", None),
("create", "create", "新建文件目录", "DirectoryCreateReq"),
("update", "update", "更新文件目录", "DirectoryUpdateReq"),
("delete", "delete", "删除文件目录", "DirectoryDeleteReq"),
]),
}
+597
View File
@@ -0,0 +1,597 @@
"""Request fields for the existing System Admin HTTP DTOs."""
REQUESTS = {
"AdminOperationLogDetailReq": {
"properties": {
"id": {"type": "integer", "minimum": 1},
},
"required": ["id"],
},
"AdminOperationLogListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "default": 20},
"operationKey": {"type": "string"},
"resultStatus": {"type": "string", "enum": ["pending", "success", "fail", "unknown"]},
"adminId": {"type": "integer"},
"resourceType": {"type": "string"},
"resourceId": {"type": "integer"},
"traceId": {"type": "string"},
"startTime": {"type": "string"},
"endTime": {"type": "string"},
},
"required": [],
},
"AliyunDNSAccountCreateReq": {
"properties": {
"name": {"type": "string", "maxLength": 120},
"status": {"type": "string", "enum": ["active", "disabled"]},
"accessKeyId": {"type": "string", "maxLength": 128},
"accessKeySecret": {"type": "string", "maxLength": 256},
},
"required": ["name", "status", "accessKeyId", "accessKeySecret"],
},
"AliyunDNSAccountCredentialReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"AliyunDNSAccountDeleteReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"version": {"type": "integer", "minimum": 1},
},
"required": ["id", "version"],
},
"AliyunDNSAccountListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
"keyword": {"type": "string", "maxLength": 120},
"status": {"type": "string", "enum": ["active", "disabled"]},
"healthStatus": {"type": "string", "enum": ["unknown", "healthy", "unhealthy"]},
},
"required": ["pageNo", "pageSize"],
},
"AliyunDNSAccountReplaceCredentialReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"version": {"type": "integer", "minimum": 1},
"accessKeyId": {"type": "string", "maxLength": 128},
"accessKeySecret": {"type": "string", "maxLength": 256},
},
"required": ["id", "version", "accessKeyId", "accessKeySecret"],
},
"AliyunDNSAccountStatusReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"version": {"type": "integer", "minimum": 1},
"status": {"type": "string", "enum": ["active", "disabled"]},
},
"required": ["id", "version", "status"],
},
"AliyunDNSAccountUpdateReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"version": {"type": "integer", "minimum": 1},
"name": {"type": "string", "maxLength": 120},
},
"required": ["id", "version", "name"],
},
"AliyunDNSAccountValidateReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"AliyunDNSDomainListReq": {
"properties": {
"accountId": {"type": "string", "format": "uuid"},
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
"keyword": {"type": "string", "maxLength": 253},
},
"required": ["accountId", "pageNo", "pageSize"],
},
"AliyunDNSRecordDeleteReq": {
"properties": {
"accountId": {"type": "string", "format": "uuid"},
"domainName": {"type": "string", "maxLength": 253},
"recordId": {"type": "string"},
},
"required": ["accountId", "domainName", "recordId"],
},
"AliyunDNSRecordListReq": {
"properties": {
"accountId": {"type": "string", "format": "uuid"},
"domainName": {"type": "string", "maxLength": 253},
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
"rr": {"type": "string", "maxLength": 253},
"type": {"type": "string", "maxLength": 16},
"value": {"type": "string", "maxLength": 2048},
"status": {"type": "string", "enum": ["ENABLE", "DISABLE"]},
},
"required": ["accountId", "domainName", "pageNo", "pageSize"],
},
"AliyunDNSRecordMutationReq": {
"properties": {
"accountId": {"type": "string", "format": "uuid"},
"domainName": {"type": "string", "maxLength": 253},
"rr": {"type": "string", "maxLength": 253},
"type": {"type": "string", "enum": ["A", "AAAA", "CNAME", "TXT", "MX", "NS", "SRV", "CAA"]},
"value": {"type": "string", "maxLength": 2048},
"ttl": {"type": "integer", "minimum": 1},
"priority": {"type": "integer", "minimum": 0, "maximum": 50},
"line": {"type": "string", "const": "default"},
},
"required": ["accountId", "domainName", "rr", "type", "value", "ttl", "line"],
},
"AliyunDNSRecordOptionsReq": {
"properties": {
"accountId": {"type": "string", "format": "uuid"},
"domainName": {"type": "string", "maxLength": 253},
},
"required": ["accountId", "domainName"],
},
"AliyunDNSRecordStatusReq": {
"properties": {
"accountId": {"type": "string", "format": "uuid"},
"domainName": {"type": "string", "maxLength": 253},
"recordId": {"type": "string"},
"status": {"type": "string", "enum": ["ENABLE", "DISABLE"]},
},
"required": ["accountId", "domainName", "recordId", "status"],
},
"AliyunDNSRecordUpdateReq": {
"properties": {
"accountId": {"type": "string", "format": "uuid"},
"domainName": {"type": "string", "maxLength": 253},
"rr": {"type": "string", "maxLength": 253},
"type": {"type": "string", "enum": ["A", "AAAA", "CNAME", "TXT", "MX", "NS", "SRV", "CAA"]},
"value": {"type": "string", "maxLength": 2048},
"ttl": {"type": "integer", "minimum": 1},
"priority": {"type": "integer", "minimum": 0, "maximum": 50},
"line": {"type": "string", "const": "default"},
"recordId": {"type": "string"},
},
"required": ["accountId", "domainName", "rr", "type", "value", "ttl", "line", "recordId"],
},
"CreateFieldCheckTaskReq": {
"properties": {
"tables": {"type": "array", "minItems": 1, "items": {"type": "string"}},
},
"required": ["tables"],
},
"CreateModuleTaskReq": {
"properties": {
"modules": {"type": "array", "minItems": 1, "items": {"type": "string"}},
},
"required": ["modules"],
},
"CreateSmartTaskReq": {
"properties": {
"modules": {"type": "array", "minItems": 1, "items": {"type": "string"}},
},
"required": ["modules"],
},
"CreateTableTaskReq": {
"properties": {
"tables": {"type": "array", "minItems": 1, "items": {"type": "string"}},
},
"required": ["tables"],
},
"DirectoryCreateReq": {
"properties": {
"name": {"type": "string", "maxLength": 100},
"parentId": {"type": "integer"},
},
"required": ["name"],
},
"DirectoryDeleteReq": {
"properties": {
"id": {"type": "integer", "minimum": 1},
},
"required": ["id"],
},
"DirectoryUpdateReq": {
"properties": {
"id": {"type": "integer", "minimum": 1},
"name": {"type": "string", "maxLength": 100},
},
"required": ["id", "name"],
},
"DownloadFromUrlReq": {
"properties": {
"url": {"type": "string", "format": "uri"},
"path": {"type": "string"},
},
"required": ["url"],
},
"LightCoreStorageBucketCreateReq": {
"properties": {
"name": {"type": "string", "maxLength": 120},
"status": {"type": "string", "enum": ["active", "read_only", "disabled"]},
"originIds": {"type": "array", "minItems": 1, "items": {"type": "string", "format": "uuid"}},
},
"required": ["name", "status", "originIds"],
},
"LightCoreStorageBucketDetailReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"LightCoreStorageBucketListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
"keyword": {"type": "string", "maxLength": 120},
"status": {"type": "string", "enum": ["active", "read_only", "disabled"]},
},
"required": ["pageNo", "pageSize"],
},
"LightCoreStorageBucketStatusReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"status": {"type": "string", "enum": ["active", "read_only", "disabled"]},
},
"required": ["id", "status"],
},
"LightCoreStorageBucketUpdateRouteReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"originIds": {"type": "array", "minItems": 1, "items": {"type": "string", "format": "uuid"}},
},
"required": ["id", "originIds"],
},
"LightCoreStorageClientCreateReq": {
"properties": {
"clientName": {"type": "string", "maxLength": 120},
"status": {"type": "string", "enum": ["active", "disabled"]},
"grants": {"type": "array", "minItems": 1, "items": {"type": "object", "properties": {"bucketId": {"type": "string", "format": "uuid"}, "canRead": {"type": "boolean"}, "canWrite": {"type": "boolean"}, "canDelete": {"type": "boolean"}}, "required": ["bucketId"]}},
},
"required": ["clientName", "status", "grants"],
},
"LightCoreStorageClientDetailReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"LightCoreStorageClientListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
"keyword": {"type": "string", "maxLength": 120},
"status": {"type": "string", "enum": ["active", "disabled"]},
},
"required": ["pageNo", "pageSize"],
},
"LightCoreStorageClientNameReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"clientName": {"type": "string", "maxLength": 120},
},
"required": ["id", "clientName"],
},
"LightCoreStorageClientReplaceGrantsReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"grants": {"type": "array", "minItems": 1, "items": {"type": "object", "properties": {"bucketId": {"type": "string", "format": "uuid"}, "canRead": {"type": "boolean"}, "canWrite": {"type": "boolean"}, "canDelete": {"type": "boolean"}}, "required": ["bucketId"]}},
},
"required": ["id", "grants"],
},
"LightCoreStorageClientSecretReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"LightCoreStorageClientStatusReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"status": {"type": "string", "enum": ["active", "disabled"]},
},
"required": ["id", "status"],
},
"LightCoreStorageObjectActionReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"LightCoreStorageObjectDetailReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"LightCoreStorageObjectListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
"bucketId": {"type": "string", "format": "uuid"},
"clientId": {"type": "string", "format": "uuid"},
"originId": {"type": "string", "format": "uuid"},
"status": {"type": "string", "enum": ["pending", "active", "upload_failed", "deleting", "delete_failed", "deleted"]},
"mimeType": {"type": "string", "maxLength": 255},
"startAt": {"type": "string"},
"endAt": {"type": "string"},
},
"required": ["pageNo", "pageSize"],
},
"LightCoreStorageObjectURLReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"expiresInSeconds": {"type": "integer", "minimum": 60, "maximum": 86400},
},
"required": ["id"],
},
"LightCoreStorageOriginActionReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"LightCoreStorageOriginCreateReq": {
"properties": {
"name": {"type": "string", "maxLength": 120},
"provider": {"type": "string", "enum": ["alioss", "tencent_cos", "qiniu", "aws_s3", "minio"]},
"status": {"type": "string", "enum": ["active", "disabled"]},
"accessKey": {"type": "string", "maxLength": 1000},
"secretKey": {"type": "string"},
"physicalBucket": {"type": "string", "maxLength": 255},
"region": {"type": "string", "maxLength": 120},
"endpoint": {"type": "string", "maxLength": 500},
"pathPrefix": {"type": "string", "maxLength": 500},
"cdnDomain": {"type": "string", "maxLength": 500},
"appId": {"type": "string", "maxLength": 255},
"useSsl": {"type": "boolean", "examples": [True]},
"usePathStyle": {"type": "boolean"},
"supportsPublicRead": {"type": "boolean", "examples": [True]},
"supportsPrivate": {"type": "boolean"},
},
"required": ["name", "provider", "status", "accessKey", "secretKey", "physicalBucket"],
},
"LightCoreStorageOriginCredentialReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"LightCoreStorageOriginDetailReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"LightCoreStorageOriginListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
"keyword": {"type": "string", "maxLength": 120},
"provider": {"type": "string", "enum": ["alioss", "tencent_cos", "qiniu", "aws_s3", "minio"]},
"status": {"type": "string", "enum": ["active", "disabled"]},
"healthStatus": {"type": "string", "enum": ["unknown", "healthy", "unhealthy"]},
},
"required": ["pageNo", "pageSize"],
},
"LightCoreStorageOriginReplaceCredentialReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"credentialVersion": {"type": "integer", "minimum": 1},
"accessKey": {"type": "string", "maxLength": 1000},
"secretKey": {"type": "string"},
},
"required": ["id", "credentialVersion", "accessKey", "secretKey"],
},
"LightCoreStorageOriginStatusReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"status": {"type": "string", "enum": ["active", "disabled"]},
},
"required": ["id", "status"],
},
"LightCoreStorageOriginUpdateReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"name": {"type": "string", "maxLength": 120},
"status": {"type": "string", "enum": ["active", "disabled"]},
"physicalBucket": {"type": "string", "maxLength": 255},
"region": {"type": "string", "maxLength": 120},
"endpoint": {"type": "string", "maxLength": 500},
"pathPrefix": {"type": "string", "maxLength": 500},
"cdnDomain": {"type": "string", "maxLength": 500},
"appId": {"type": "string", "maxLength": 255},
"useSsl": {"type": "boolean", "examples": [True]},
"usePathStyle": {"type": "boolean"},
"supportsPublicRead": {"type": "boolean", "examples": [True]},
"supportsPrivate": {"type": "boolean"},
},
"required": ["id", "name", "status", "physicalBucket"],
},
"MoveToDirectoryReq": {
"properties": {
"id": {"type": "integer", "minimum": 1},
"directoryId": {"type": "integer"},
},
"required": ["id"],
},
"RenameFileReq": {
"properties": {
"id": {"type": "integer", "minimum": 1},
"newName": {"type": "string", "maxLength": 255},
},
"required": ["id", "newName"],
},
"RequestTraceDetailReq": {
"properties": {
"requestId": {"type": "string"},
},
"required": ["requestId"],
},
"RequestTraceListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "default": 20},
"requestId": {"type": "string"},
"channel": {"type": "string"},
"moduleKey": {"type": "string"},
"method": {"type": "string"},
"path": {"type": "string"},
"successStatus": {"type": "string", "enum": ["success", "fail"]},
"startTime": {"type": "string"},
"endTime": {"type": "string"},
},
"required": [],
},
"SSLCertificateAccountGetListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "maximum": 200, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
"environment": {"type": "string", "enum": ["production", "staging"]},
"email": {"type": "string", "maxLength": 254, "format": "email"},
"status": {"type": "string", "enum": ["registering", "valid", "failed", "unknown"]},
},
"required": ["pageNo", "pageSize"],
},
"SSLCertificateAccountGetTermsReq": {
"properties": {
"environment": {"type": "string", "enum": ["production", "staging"]},
},
"required": ["environment"],
},
"SSLCertificateAccountRegisterReq": {
"properties": {
"environment": {"type": "string", "enum": ["production", "staging"]},
"email": {"type": "string", "maxLength": 254, "format": "email"},
"termsUrl": {"type": "string", "maxLength": 1024, "format": "uri"},
"acceptTerms": {"type": "boolean", "const": True},
},
"required": ["environment", "email", "termsUrl", "acceptTerms"],
},
"SSLCertificateRequestCreateReq": {
"properties": {
"name": {"type": "string", "maxLength": 120},
"accountId": {"type": "string", "format": "uuid"},
"domains": {"type": "array", "minItems": 1, "maxItems": 100, "items": {"type": "string", "maxLength": 253}},
"keyType": {"type": "string", "enum": ["rsa-2048", "ecdsa-p256"]},
},
"required": ["name", "accountId", "domains", "keyType"],
},
"SSLCertificateRequestDeleteReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
"version": {"type": "integer", "minimum": 1},
},
"required": ["id", "version"],
},
"SSLCertificateRequestGetListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "maximum": 200, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
"keyword": {"type": "string", "maxLength": 120},
"environment": {"type": "string", "enum": ["production", "staging"]},
"accountId": {"type": "string", "format": "uuid"},
"domain": {"type": "string", "maxLength": 253},
"status": {"type": "string", "enum": ["ordering", "waiting_dns", "ready_to_issue", "validation_pending", "validating", "issuing", "issued", "failed", "unknown", "expired"]},
},
"required": ["pageNo", "pageSize"],
},
"SSLCertificateRequestIDReq": {
"properties": {
"id": {"type": "string", "format": "uuid"},
},
"required": ["id"],
},
"SystemHttpLogBatchDeleteReq": {
"properties": {
"ids": {"type": "array", "minItems": 1, "items": {"type": "integer"}},
},
"required": ["ids"],
},
"SystemHttpLogDeleteReq": {
"properties": {
"id": {"type": "integer", "minimum": 1},
},
"required": ["id"],
},
"SystemHttpLogDetailReq": {
"properties": {
"id": {"type": "integer"},
},
"required": [],
},
"SystemHttpLogListReq": {
"properties": {
"direction": {"type": "string", "enum": ["inbound", "outbound"]},
"source": {"type": "string"},
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "default": 20},
"method": {"type": "string"},
"requestUrl": {"type": "string"},
"responseStatus": {"type": "integer"},
"successStatus": {"type": "string", "enum": ["success", "fail"]},
"startTime": {"type": "string"},
"endTime": {"type": "string"},
},
"required": [],
},
"TableCheckReq": {
"properties": {
"module": {"type": "string"},
},
"required": [],
},
"TaskDetailReq": {
"properties": {
"id": {"type": "integer"},
},
"required": ["id"],
},
"TaskListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20},
},
"required": ["pageNo", "pageSize"],
},
"UpdatePasswordReq": {
"properties": {
"oldPassword": {"type": "string"},
"newPassword": {"type": "string"},
},
"required": ["oldPassword", "newPassword"],
},
"UploadFilesDeleteReq": {
"properties": {
"id": {"type": "integer", "minimum": 1},
},
"required": ["id"],
},
"UploadFilesDetailReq": {
"properties": {
"id": {"type": "integer", "minimum": 1},
},
"required": ["id"],
},
"UploadFilesListReq": {
"properties": {
"pageNo": {"type": "integer", "minimum": 1, "default": 1},
"pageSize": {"type": "integer", "minimum": 1, "default": 20},
"name": {"type": "string"},
"type": {"type": "string", "enum": ["image", "video", "file"]},
"directoryId": {"type": ["integer", "null"]},
},
"required": ["pageNo", "pageSize"],
},
"UploadFilesMultipart": {
"properties": {
"file": {"type": "string", "format": "binary"},
"businessCategory": {"type": "string", "default": "images"},
},
"required": ["file"],
},
}
+444
View File
@@ -0,0 +1,444 @@
"""HTTP, authentication and file transfer for LightCore applications."""
import contextlib
import errno
import getpass
from http.client import IncompleteRead
import ipaddress
import json
import mimetypes
import os
from pathlib import Path
import re
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,
'gysmart': 'https://am.gysmart.shop'}
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:
"""可重复打开的有长度流;仅认证失效允许一次重发。"""
def __init__(self, file, fields):
self.file = Path(file).resolve()
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 对象,字段值为字符串、数字或布尔值。')
if not self.file.is_file():
raise ClientError('上传文件不存在。')
self.stat = self.file.stat()
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):
current = self.file.stat()
if (current.st_size, current.st_mtime_ns) != (self.stat.st_size, self.stat.st_mtime_ns):
raise ClientError('上传文件已变化,未继续发送。')
yield self.prefix
with self.file.open('rb') as stream:
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
self.refreshable = self.app in ('shop', 'media')
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]))
return base_url(next((value for value in candidates if value and value.strip()), DEFAULT_BASE_URLS[self.app]), self.app)
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()
try:
size = 0
with private_output(target) as stream:
while chunk := response.read(1024 * 1024):
stream.write(chunk)
size += len(chunk)
expected = response.headers.get('Content-Length')
if expected is not None and size != int(expected):
raise ClientError('下载长度不完整,未保存目标文件。', **details)
return {'ok': True, **details, 'downloaded': True, 'outputFile': str(target), 'bytes': size}
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)
try:
try:
response = self.http.open(request, timeout=self.timeout)
except HTTPError as error:
response = error
with response:
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')
trace_id = response.headers.get('X-Request-ID')
status = response.status
except (URLError, OSError, TimeoutError, IncompleteRead, ValueError):
raise ClientError('HTTP 请求未获得完整响应,结果未知;写操作请先核对业务结果,不要盲目重试。') from None
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
def login_base(self, explicit_base):
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('目标文件已有其他或未标明应用的会话,拒绝覆盖,请使用独立会话文件。')
return self.configured_base(previous, explicit_base)
def login(self, explicit_base=None):
base = self.login_base(explicit_base)
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):
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
+16
View File
@@ -0,0 +1,16 @@
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[project]
name = "lightcore-cli"
version = "0.3.2"
description = "Command-line client for LightCore applications"
readme = "README.md"
requires-python = ">=3.10"
[project.scripts]
lightcore = "lightcore_cli.cli:main"
[tool.setuptools]
packages = ["lightcore_cli"]
+311
View File
@@ -0,0 +1,311 @@
import argparse
from contextlib import redirect_stderr, redirect_stdout
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import io
import json
import os
from pathlib import Path
import re
from tempfile import TemporaryDirectory
from threading import Thread
import time
import unittest
from unittest.mock import patch
from lightcore_cli.cli import default_session, main, parser
class MediaHandler(BaseHTTPRequestHandler):
requests = []
prefix = "/api/media/admin"
def log_message(self, *_):
pass
def reply(self, data, *, code=200, message=""):
raw = json.dumps({"code": code, "data": data, "msg": message}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
body = self.rfile.read(int(self.headers["Content-Length"]))
path = self.path.removeprefix(self.prefix)
self.requests.append((path, self.headers.get("Authorization"), body))
if path == "/auth/login":
credentials = json.loads(body)
if credentials["username"] == "unavailable":
return self.reply(None, code=400, message="登录服务暂时不可用")
if credentials != {"username": "synthetic-user", "password": "synthetic-valid"}:
return self.reply(None, code=400, message="用户名或密码错误")
self.reply({"accessToken": "fresh-access", "refreshToken": "fresh-refresh",
"accessTokenExpiresAt": int(time.time()) + 600,
"refreshTokenExpiresAt": int(time.time()) + 1200})
elif path == "/auth/refresh":
self.reply({"accessToken": "fresh-access", "refreshToken": "fresh-refresh",
"accessTokenExpiresAt": int(time.time()) + 600,
"refreshTokenExpiresAt": int(time.time()) + 1200})
elif path in ("/auth/logout", "/auth/changePassword"):
self.reply(None)
elif path == "/content/social/getAccountList":
self.reply({"total": 0, "list": []})
elif path == "/content/social/saveContent":
self.reply({"id": 58, "updatedAt": "2026-11-20T12:00:00Z"})
elif path == "/storage/getConfig":
self.reply({"bucket": "media", "clientSecret": "synthetic-storage-secret"})
elif path == "/content/document/getDocumentList":
self.reply({"total": 1, "list": [{"id": 58, "title": "推窗器", "snippet": "ignored"}]})
elif path == "/content/document/getDocumentDetail":
self.reply({"files": [{"id": 123, "fileName": "../说明书.pdf", "mimeType": "application/pdf",
"fileSize": 3, "previewUrl": "https://example.test/?signature=synthetic"}]})
elif path == "/content/social/uploadAsset":
self.reply({"id": 123, "fileName": "ignored"})
elif path == "/content/document/downloadAsset":
self.send_response(200)
self.send_header("Content-Type", "application/pdf")
self.send_header("Content-Disposition", "attachment; filename=manual.pdf")
self.send_header("Content-Length", "3")
self.end_headers()
self.wfile.write(b"PDF")
else:
self.send_error(404)
class MediaCliTests(unittest.TestCase):
def setUp(self):
environment = patch.dict(os.environ, {"LIGHTCORE_API_BASE_URL": ""})
environment.start()
self.addCleanup(environment.stop)
tmp = TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = Path(tmp.name)
server = ThreadingHTTPServer(("127.0.0.1", 0), MediaHandler)
self.addCleanup(server.server_close)
thread = Thread(target=server.serve_forever)
thread.start()
self.addCleanup(thread.join)
self.addCleanup(server.shutdown)
MediaHandler.requests.clear()
self.session = self.root / ".env"
self.session.write_text(
f"LIGHTCORE_API_BASE_URL=http://127.0.0.1:{server.server_port}\n"
"LIGHTCORE_API_APP=media\n"
"LIGHTCORE_ACCESS_TOKEN=old-access\n"
"LIGHTCORE_REFRESH_TOKEN=old-refresh\n"
f"LIGHTCORE_ACCESS_TOKEN_EXPIRES_AT={int(time.time()) - 1}\n"
f"LIGHTCORE_REFRESH_TOKEN_EXPIRES_AT={int(time.time()) + 1200}\n",
encoding="utf-8",
)
def invoke_media(self, *args, expected=0):
out = io.StringIO()
with redirect_stdout(out), redirect_stderr(io.StringIO()):
status = main(["media", "--env-file", str(self.session), *args])
self.assertEqual(status, expected, out.getvalue())
self.assertNotIn("fresh-access", out.getvalue())
self.assertNotIn("signature=", out.getvalue())
return json.loads(out.getvalue())
def invoke(self, *args, expected=0):
return self.invoke_media("files", *args, expected=expected)
def test_login_prompts_again_after_rejected_credentials(self):
stderr = io.StringIO()
with patch("builtins.input", side_effect=["wrong-user", "synthetic-user"]), \
patch("lightcore_cli.transport.getpass.getpass",
side_effect=["synthetic-wrong", "synthetic-valid"]), \
redirect_stdout(io.StringIO()) as stdout, redirect_stderr(stderr):
self.assertEqual(main(["media", "--env-file", str(self.session), "login"]), 0)
self.assertTrue(json.loads(stdout.getvalue())["ok"])
self.assertIn("重新输入账号和密码", stderr.getvalue())
self.assertNotIn("synthetic", stdout.getvalue() + stderr.getvalue())
self.assertEqual([json.loads(request[2]) for request in MediaHandler.requests], [
{"username": "wrong-user", "password": "synthetic-wrong"},
{"username": "synthetic-user", "password": "synthetic-valid"},
])
self.assertIn("LIGHTCORE_ACCESS_TOKEN=fresh-access", self.session.read_text(encoding="utf-8"))
def test_login_does_not_repeat_on_service_failure(self):
with patch("builtins.input", return_value="unavailable") as account, \
patch("lightcore_cli.transport.getpass.getpass", return_value="synthetic-password"):
self.assertFalse(self.invoke_media("login", expected=1)["ok"])
account.assert_called_once()
self.assertEqual(len(MediaHandler.requests), 1)
def test_find_and_list_reuse_refreshed_session(self):
result = self.invoke("find", "--keyword", "推窗器")
self.assertEqual(result["items"], [{"documentId": 58, "title": "推窗器"}])
result = self.invoke("list", "--document-id", "58")
self.assertEqual(result["items"][0]["fileId"], 123)
self.assertEqual(len(MediaHandler.requests), 3)
self.assertEqual(MediaHandler.requests[0][0], "/auth/refresh")
self.assertEqual(json.loads(MediaHandler.requests[0][2]), {"refreshToken": "old-refresh"})
self.assertEqual(MediaHandler.requests[1][1], "Bearer fresh-access")
self.assertEqual(json.loads(MediaHandler.requests[1][2]), {
"keyword": "推窗器", "pageNo": 1, "pageSize": 10,
})
self.assertEqual(MediaHandler.requests[2][1], "Bearer fresh-access")
def test_upload_stream_and_compact_receipt(self):
source = self.root / "说明书.pdf"
source.write_bytes(b"%PDF-synthetic")
result = self.invoke("upload", str(source), "--request-id", "814138da-aa09-4936-b76f-e4e18e007872")
self.assertEqual(result, {"ok": True, "fileId": 123})
path, auth, body = MediaHandler.requests[-1]
self.assertEqual((path, auth), ("/content/social/uploadAsset", "Bearer fresh-access"))
self.assertIn(b"814138da-aa09-4936-b76f-e4e18e007872", body)
self.assertIn(source.read_bytes(), body)
def test_get_validates_scope_and_preserves_existing_files(self):
result = self.invoke("get", "--document-id", "58", "--file-id", "123", "--file-id", "124",
"--output-dir", str(self.root), expected=1)
downloaded, missing = result["items"]
self.assertTrue(downloaded["ok"])
self.assertFalse(missing["ok"])
path = Path(downloaded["outputFile"])
self.assertEqual(path.parent, self.root)
self.assertEqual(path.read_bytes(), b"PDF")
self.assertEqual(json.loads(MediaHandler.requests[-1][2]), {"documentId": 58, "fileId": 123})
result = self.invoke("get", "--document-id", "58", "--file-id", "123",
"--output-dir", str(self.root), expected=1)
self.assertFalse(result["items"][0]["ok"])
self.assertEqual(path.read_bytes(), b"PDF")
self.assertEqual(sum(req[0].endswith("/downloadAsset") for req in MediaHandler.requests), 1)
def test_default_session_for_checkout_and_standalone_install(self):
lightcore = self.root / "LightCore"
(lightcore / "scripts").mkdir(parents=True)
(lightcore / "scripts" / "lightcore_api.py").touch()
plan = self.root / "plan"
(plan / "工具").mkdir(parents=True)
(plan / "工具" / "README.md").touch()
(plan / "业务").mkdir()
(plan / "业务" / "README.md").touch()
for workspace in (lightcore / "projects", plan / "业务"):
with patch.object(Path, "cwd", return_value=workspace):
self.assertEqual(default_session("media"),
lightcore / ".work/lightcore-api/media/.env")
with patch.object(Path, "cwd", return_value=self.root / "standalone"), \
patch.object(Path, "home", return_value=self.root / "user"):
self.assertEqual(default_session("media"),
self.root / "user/.lightcore/lightcore-api/media/.env")
def test_generic_request_and_download_share_media_session(self):
common = ["--app", "media", "--env-file", str(self.session)]
output = self.root / "manual.pdf"
for args in (
["request", *common, "--path", "/content/document/getDocumentDetail",
"--body", '{"documentId":58}'],
["download", *common, "--path", "/content/document/downloadAsset",
"--body", '{"documentId":58,"fileId":123}', "--output", str(output)],
):
stdout = io.StringIO()
with redirect_stdout(stdout):
self.assertEqual(main(["api", *args]), 0)
self.assertTrue(json.loads(stdout.getvalue())["ok"])
self.assertEqual(output.read_bytes(), b"PDF")
self.assertEqual([item[0] for item in MediaHandler.requests], [
"/auth/refresh", "/content/document/getDocumentDetail", "/content/document/downloadAsset",
])
def test_dedicated_commands_use_filters_and_preserve_write_payload(self):
self.invoke_media("accounts", "list", "--is-valid", "false", "--page-size", "1")
path, _, body = MediaHandler.requests[-1]
self.assertEqual(path, "/content/social/getAccountList")
self.assertEqual(json.loads(body), {"pageNo": 1, "pageSize": 1, "isValid": False})
payload = {"contentId": 58, "expectedUpdatedAt": "2026-11-20T11:59:00.123456789Z",
"requestId": "814138da-aa09-4936-b76f-e4e18e007872", "mediaFileIds": []}
body_file = self.root / "update.json"
body_file.write_text(json.dumps(payload), encoding="utf-8-sig")
result = self.invoke_media("contents", "save", "--body-file", str(body_file))
self.assertEqual(result["body"]["data"]["id"], 58)
self.assertEqual(MediaHandler.requests[-1][0], "/content/social/saveContent")
self.assertEqual(json.loads(MediaHandler.requests[-1][2]), payload)
def test_storage_redaction_and_explicit_authentication_operations(self):
self.invoke_media("auth", "refresh")
storage = self.invoke_media("storage", "get")
self.assertEqual(storage["body"]["data"]["clientSecret"], "[REDACTED]")
self.invoke_media("auth", "logout")
self.assertEqual(MediaHandler.requests[-1][:2], ("/auth/logout", "Bearer fresh-access"))
self.assertEqual(json.loads(MediaHandler.requests[-1][2]), {"refreshToken": "fresh-refresh"})
local = self.session.read_text(encoding="utf-8")
self.assertNotIn("TOKEN=", local)
self.assertIn("LIGHTCORE_API_APP=media", local)
def test_sensitive_command_requires_private_body_file(self):
with redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
parser().parse_args(["media", "auth", "change-password", "--body", "{}"])
def test_command_help_shows_limits_and_enum_values(self):
stdout = io.StringIO()
with redirect_stdout(stdout), self.assertRaises(SystemExit) as exit:
main(["media", "contents", "list", "--help"])
self.assertEqual(exit.exception.code, 0)
self.assertIn("--page-size", stdout.getvalue())
self.assertIn("范围 1–100,默认 20", stdout.getvalue())
self.assertIn("image_text / video", stdout.getvalue())
def test_write_descriptions_work_without_a_session(self):
def describe(group, operation, *flags):
stdout = io.StringIO()
args = ["media", "--env-file", str(self.root / "missing.env"), group, operation, *flags]
with redirect_stdout(stdout), patch("lightcore_cli.cli.Client") as client, self.assertRaises(SystemExit) as exit:
main(args)
self.assertEqual(exit.exception.code, 0)
client.assert_not_called()
return json.loads(stdout.getvalue())
schema = describe("videos", "save", "--schema")
self.assertEqual(schema["else"]["required"], ["requestId", "episodeId", "name"])
self.assertEqual(schema["then"]["required"], ["requestId", "videoId", "expectedUpdatedAt"])
self.assertEqual(schema["properties"]["videoId"]["minimum"], 0)
self.assertEqual(schema["if"]["properties"]["videoId"]["minimum"], 1)
image = schema["properties"]["referenceImages"]["items"]
self.assertEqual(image["required"], ["name"])
self.assertEqual(image["properties"]["frameRole"]["enum"], ["reference", "first", "last"])
self.assertEqual(image["properties"]["referenceFileIds"]["items"]["type"], "integer")
create = describe("videos", "save", "--example")
self.assertTrue(set(schema["else"]["required"]).issubset(create))
self.assertEqual(create["referenceImages"][0]["frameRole"], "reference")
update = describe("videos", "save", "--example", "update")
self.assertEqual(update.keys(), {"requestId", "videoId", "expectedUpdatedAt", "body"})
storage = describe("storage", "save", "--example")
self.assertEqual(storage["clientSecret"], "REPLACE_WITH_CLIENT_SECRET")
self.assertFalse(MediaHandler.requests)
def test_media_cli_covers_registered_backend_routes(self):
root = Path(__file__).resolve().parents[3] if len(Path(__file__).resolve().parents) >= 4 else Path(".")
controllers = root / "backend/application/media/interfaces/admin/controllers"
if not controllers.is_dir():
self.skipTest("独立安装目录没有 Go 后台路由源码")
routes = set()
for source in controllers.glob("*.go"):
text = source.read_text(encoding="utf-8")
group = re.search(r'\.Group\("(/content/[^"]+)"', text)
base = re.search(r'base := "(/content/[^"]+/)"', text)
for direct, suffix in re.findall(r'\br\.Handle\("POST",\s*(?:"([^"]+)"|base\s*\+\s*"([^"]+)")', text):
routes.add((group[1] if group else "") + direct if direct else base[1] + suffix)
self.assertTrue(routes)
def endpoints(command):
values = set()
if command.get_default("endpoint"):
values.add(command.get_default("endpoint"))
for action in command._actions:
if isinstance(action, argparse._SubParsersAction):
for child in action.choices.values():
values.update(endpoints(child))
return values
media_command = next(action.choices["media"] for action in parser()._actions
if isinstance(action, argparse._SubParsersAction))
self.assertSetEqual(endpoints(media_command), routes)
if __name__ == "__main__":
unittest.main()
+236
View File
@@ -0,0 +1,236 @@
import base64
from contextlib import redirect_stdout
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import io
import json
import os
from pathlib import Path
import re
from tempfile import TemporaryDirectory
from threading import Thread
import time
import unittest
from unittest.mock import patch
import zipfile
from lightcore_cli.cli import main, parser
from lightcore_cli.system_routes import GROUPS
def sample_token():
claims = json.dumps({"exp": int(time.time()) + 600}).encode()
payload = base64.urlsafe_b64encode(claims).decode().rstrip("=")
return f"e30.{payload}.synthetic-signature"
class SystemHTTP(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def reply(self, data=None, *, code=200, message="", content_type="application/json", attachment=False):
payload = (json.dumps({"code": code, "data": data, "msg": message}).encode()
if content_type == "application/json" else data)
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(payload)))
self.send_header("X-Request-ID", "system-request-test")
if attachment:
self.send_header("Content-Disposition", 'attachment; filename="certificate.zip"')
self.end_headers()
self.wfile.write(payload)
def do_POST(self):
body = self.rfile.read(int(self.headers["Content-Length"]))
self.server.requests.append((self.path, self.headers.get("Authorization"), body))
if self.path == "/api/admin/login/account":
if json.loads(body)["username"] == "test-user":
return self.reply({"status": "ok", "token": self.server.token})
return self.reply({"status": "error", "currentAuthority": "guest"})
if self.headers.get("Authorization") != f"Bearer {self.server.token}" or self.server.rejected:
return self.reply(code=1001, message="会话失效")
if self.path == "/api/admin/login/outLogin":
return self.reply({"success": True})
if self.path == "/api/admin/user/updatePassword":
return self.reply({"success": False, "message": "旧密码错误"})
if self.path == "/api/admin/dbMigrate/createModuleTask":
return self.reply({"created": True, "task": {"id": 17, "status": "pending"}})
if self.path == "/api/admin/dbMigrate/getTaskDetail":
return self.reply({"id": 17, "status": "success"})
if self.path == "/api/admin/sslCertificateRequest/issue":
if self.server.drop_response:
self.close_connection = True
return
return self.reply({"status": "validation_pending"})
if self.path == "/api/admin/uploadFiles/upload":
return self.reply({"id": 15, "contentType": self.headers["Content-Type"]})
if self.path == "/api/admin/aliyunDnsAccount/getCredential":
return self.reply({"accessKeySecret": "synthetic-secret-for-test"})
if self.path == "/api/admin/lightCoreStorageObject/getURL":
return self.reply({"url": "https://example.invalid/object?sig=synthetic-signature"})
if self.path == "/api/admin/sslCertificateRequest/download":
if self.server.reject_zip:
return self.reply(code=400, message="证书未签发", attachment=True)
archive = io.BytesIO()
with zipfile.ZipFile(archive, "w") as zip_output:
zip_output.writestr("cert.pem", b"synthetic public certificate")
return self.reply(archive.getvalue(), content_type="application/zip", attachment=True)
self.reply({"id": 1})
class SystemRouteTests(unittest.TestCase):
def test_every_backend_route_has_one_named_command(self):
root = Path(__file__).resolve().parents[3]
controllers = root / "backend/application/system/interfaces/admin/controllers"
registered = [
path
for source in controllers.glob("*.go") if not source.stem.endswith("_test")
for path in re.findall(r'\.Handle\("POST", "([^"]+)"', source.read_text(encoding="utf-8"))
]
cli = parser()
commands = [cli.parse_args(["system", "login"]).endpoint, cli.parse_args(["system", "logout"]).endpoint]
for group, (_, _, operations) in GROUPS.items():
for name, *operation in operations:
with self.subTest(group=group, name=name):
output = io.StringIO()
with redirect_stdout(output), self.assertRaises(SystemExit) as result:
cli.parse_args(["system", group, name, "--schema"])
self.assertEqual(result.exception.code, 0)
self.assertEqual(json.loads(output.getvalue())["type"], "object")
args = cli.parse_args([
"system", group, name,
*(["--file", "example.png"] if "upload" in operation[3:] else []),
*(["--output", "example.out"] if set(operation[3:]) & {"zip", "private-output"} else []),
*(["--body-file", "example.json"] if operation[0] in {
"updatePassword", "replaceCredential",
} or (name == "create" and group in {"dns-accounts", "storage-origins"}) else []),
])
commands.append(args.endpoint)
self.assertEqual(len(commands), len(set(commands)))
if not controllers.is_dir():
self.skipTest("独立安装目录没有 Go 后台路由源码")
self.assertCountEqual(commands, registered)
def test_offline_example_has_nested_grants(self):
output = io.StringIO()
with redirect_stdout(output), self.assertRaises(SystemExit) as result:
parser().parse_args(["system", "storage-clients", "create", "--example"])
self.assertEqual(result.exception.code, 0)
grant = json.loads(output.getvalue())["grants"][0]
self.assertEqual(set(grant), {"bucketId", "canRead", "canWrite", "canDelete"})
class SystemHTTPTests(unittest.TestCase):
def setUp(self):
temp = TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.env = self.root / "system.env"
self.server = ThreadingHTTPServer(("127.0.0.1", 0), SystemHTTP)
self.server.requests = []
self.server.token = sample_token()
self.server.reject_zip = self.server.rejected = self.server.drop_response = False
Thread(target=self.server.serve_forever, daemon=True).start()
self.addCleanup(self.server.server_close)
self.addCleanup(self.server.shutdown)
self.base = f"http://127.0.0.1:{self.server.server_port}"
def invoke(self, *args, expected=0):
output = io.StringIO()
with redirect_stdout(output):
exit_code = main(["system", "--env-file", str(self.env), *map(str, args)])
self.assertEqual(exit_code, expected, output.getvalue())
return json.loads(output.getvalue())
def login(self, username="test-user", *, expected=0):
with patch("builtins.input", return_value=username), patch("getpass.getpass", return_value="test-password"):
return self.invoke("login", "--base-url", self.base, expected=expected)
def test_session_uses_system_paths_and_logout_clears_token(self):
failure = self.login("unknown", expected=1)
self.assertEqual(failure["traceId"], "system-request-test")
self.assertFalse(self.env.exists())
with patch.dict(os.environ, {"LIGHTCORE_API_BASE_URL": "https://other.example.invalid"}):
result = self.login()
self.assertNotIn(self.server.token, json.dumps(result))
self.assertIn("LIGHTCORE_API_APP=system", self.env.read_text())
self.assertNotIn("LIGHTCORE_REFRESH_TOKEN", self.env.read_text())
self.invoke("user", "info")
self.invoke("logout")
self.assertNotIn("LIGHTCORE_ACCESS_TOKEN", self.env.read_text())
self.assertEqual([request[0] for request in self.server.requests], [
"/api/admin/login/account", "/api/admin/login/account", "/api/admin/user/currentUser",
"/api/admin/login/outLogin",
])
self.assertEqual(self.server.requests[-1][1], f"Bearer {self.server.token}")
self.invoke("user", "info", expected=1)
def test_expiry_and_rejected_session_do_not_retry(self):
self.login()
self.server.rejected = True
rejected = self.invoke("monitor", "server", expected=1)
self.assertEqual(rejected["code"], 1001)
self.assertEqual(len(self.server.requests), 2)
self.env.write_text(re.sub(r"(LIGHTCORE_ACCESS_TOKEN_EXPIRES_AT=)\d+", r"\g<1>1", self.env.read_text()))
self.invoke("monitor", "server", expected=1)
self.assertEqual(len(self.server.requests), 2)
def test_write_returns_business_failure_and_unknown_without_replay(self):
self.login()
body_file = self.root / "password.json"
body_file.write_text(json.dumps({"oldPassword": "synthetic-old", "newPassword": "synthetic-new"}))
failure = self.invoke("user", "change-password", "--body-file", body_file, expected=1)
self.assertEqual(failure["message"], "旧密码错误")
self.assertEqual(failure["traceId"], "system-request-test")
self.assertNotIn("synthetic-old", json.dumps(failure))
self.server.drop_response = True
result = self.invoke("ssl-requests", "issue", "--id", "test-id", expected=1)
self.assertIn("结果未知", result["message"])
self.assertEqual(len(self.server.requests), 3)
def test_async_tasks_and_multipart(self):
self.login()
body_file = self.root / "modules.json"
body_file.write_text('{"modules":["system"]}')
queued = self.invoke("database", "create-module-task", "--body-file", body_file)
self.assertEqual(queued["body"]["data"]["task"]["status"], "pending")
self.assertEqual(json.loads(self.server.requests[-1][2]), {"modules": ["system"]})
task = self.invoke("database", "task-detail", "--id", 17)
self.assertEqual(task["body"]["data"]["status"], "success")
issue = self.invoke("ssl-requests", "issue", "--id", "test-id")
self.assertEqual(issue["body"]["data"]["status"], "validation_pending")
document = self.root / "example.png"
document.write_bytes(b"synthetic file bytes")
upload = self.invoke("files", "upload", "--file", document, "--business-category", "images")
self.assertIn("multipart/form-data", upload["body"]["data"]["contentType"])
payload = self.server.requests[-1][2]
self.assertIn(b'name="businessCategory"\r\n\r\nimages', payload)
self.assertIn(b"synthetic file bytes", payload)
def test_private_json_and_zip_reject_overwrite_and_error_envelopes(self):
self.login()
for group, command, expected_content in [
("dns-accounts", "get-credential", "synthetic-secret-for-test"),
("storage-objects", "get-url", "sig=synthetic-signature"),
]:
target = self.root / f"{group}.json"
result = self.invoke(group, command, "--id", "test-id", "--output", target)
self.assertNotIn(expected_content, json.dumps(result))
self.assertIn(expected_content, target.read_text(encoding="utf-8"))
if os.name != "nt":
self.assertEqual(target.stat().st_mode & 0o777, 0o600)
sent_count = len(self.server.requests)
self.invoke(group, command, "--id", "test-id", "--output", target, expected=1)
self.assertEqual(len(self.server.requests), sent_count)
self.server.reject_zip = True
target = self.root / "certificate.zip"
error = self.invoke("ssl-requests", "download", "--id", "test-id", "--output", target, expected=1)
self.assertEqual(error["message"], "证书未签发")
self.assertFalse(target.exists())
self.server.reject_zip = False
self.invoke("ssl-requests", "download", "--id", "test-id", "--output", target)
with zipfile.ZipFile(target) as archive:
self.assertEqual(archive.namelist(), ["cert.pem"])
if __name__ == "__main__":
unittest.main()