Import ECS deployed relay source and historical patches (2026-10-27)

This commit is contained in:
ex_tianzy
2026-10-27 17:26:58 +08:00
commit 011a7797ee
319 changed files with 34265 additions and 0 deletions
@@ -0,0 +1,117 @@
"""Runs on the ECS; asks for App Secret on the TTY and never echoes it.
Does not send messages, create platform subscriptions, or reset device binding.
Only commits local configuration after platform credential + WS provisioning checks.
"""
import argparse
import getpass
import json
import os
import re
import shutil
import sys
import uuid
from datetime import datetime
from pathlib import Path
from urllib.parse import urlsplit
import httpx
def check_platform(base, app_id, secret, client):
results = []
for path, field in [("/open-apis/auth/v3/app_access_token/internal", "app_access_token"),
("/open-apis/auth/v3/tenant_access_token/internal", "tenant_access_token")]:
response = client.post(base + path, json={"app_id": app_id, "app_secret": secret})
if response.status_code != 200:
raise RuntimeError("platform HTTP " + str(response.status_code))
data = response.json()
if data.get("code") != 0 or not data.get(field):
code = data.get("code")
raise RuntimeError("platform code " + str(code)[:30] if isinstance(code, int) else "unexpected platform response")
results.append(field + ": valid (not displayed)")
response = client.post(base + "/callback/ws/endpoint", json={"AppID": app_id, "AppSecret": secret}, headers={"locale": "zh"})
if response.status_code != 200:
raise RuntimeError("long-connection provisioning HTTP " + str(response.status_code))
data = response.json()
if data.get("code") != 0:
code = data.get("code")
raise RuntimeError("long-connection code " + str(code)[:30] if isinstance(code, int) else "unexpected long-connection response")
url = (data.get("data") or {}).get("URL", "")
parsed = urlsplit(url)
if parsed.scheme != "wss" or not parsed.hostname:
raise RuntimeError("platform did not return a WSS endpoint")
results.append("long-connection endpoint: " + parsed.hostname + " (credential query omitted)")
return results
def update_env(path, settings):
if not path.is_file():
raise RuntimeError("existing .env missing; refusing to initialize deployment")
original = path.read_text(encoding="utf-8-sig")
backup = path.with_name(".env.before-feishu-" + datetime.now().strftime("%Y%m%d-%H%M%S-%f"))
shutil.copy2(path, backup)
backup.chmod(0o600)
lines, written = [], set()
for line in original.splitlines():
name = line.split("=", 1)[0].strip() if "=" in line and not line.lstrip().startswith("#") else ""
if name in settings:
if name not in written:
lines.append(name + "=" + settings[name])
written.add(name)
else:
lines.append(line)
lines += [name + "=" + value for name, value in settings.items() if name not in written]
temporary = path.with_name(".env.feishu-tmp-" + uuid.uuid4().hex)
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as out:
out.write("\n".join(lines) + "\n")
os.replace(temporary, path)
path.chmod(0o600)
finally:
if temporary.exists():
temporary.unlink()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--app-id", default="cli_a8733bb23078d3c7")
parser.add_argument("--api-base", default="https://open.w.cnooc.com.cn")
args = parser.parse_args()
base = args.api_base.rstrip("/")
parts = urlsplit(base)
if parts.scheme != "https" or not parts.hostname or parts.path or parts.query or parts.fragment or parts.username or parts.password:
raise RuntimeError("API base must be HTTPS origin only; do not append /app/")
if not re.fullmatch(r"cli_[a-zA-Z0-9]{16}", args.app_id):
raise RuntimeError("invalid App ID format")
if not sys.stdin.isatty():
raise RuntimeError("TTY required; use docker run -it so the secret stays hidden")
secret = getpass.getpass("App Secret (hidden input): ")
if not re.fullmatch(r"[A-Za-z0-9_-]{16,256}", secret):
raise RuntimeError("invalid App Secret shape; nothing saved")
# Never follow HTTP redirects carrying credentials, trust proxy environment,
# print upstream bodies, or disable TLS verification.
with httpx.Client(timeout=20, follow_redirects=False, trust_env=False) as client:
results = check_platform(base, args.app_id, secret, client)
update_env(args.root / ".env", {
"HN_FEISHU_APP_ID": args.app_id, "HN_FEISHU_APP_SECRET": secret,
"HN_FEISHU_API_BASE": base,
"HN_FEISHU_AUTHORIZE_URL": base + "/open-apis/authen/v1/authorize",
"HN_FEISHU_ENABLED": "true", "HN_FEISHU_EVENT_SOURCE": "longconn", "HN_OAUTH_ENABLED": "false",
})
for result in results:
print(result)
print("Configuration saved on this ECS; secret/token not displayed. OAuth remains disabled pending callback verification.")
if __name__ == "__main__":
try:
main()
except Exception as error:
if isinstance(error, RuntimeError):
print("Configuration not completed: " + str(error), file=sys.stderr)
else:
print("Configuration not completed: " + type(error).__name__ + "; no credentials displayed", file=sys.stderr)
raise SystemExit(1) from None