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
@@ -0,0 +1,43 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
test -f .env || { echo 'Missing existing .env'; exit 1; }
test -d wheelhouse || { echo 'Missing existing wheelhouse'; exit 1; }
backup_tag="hainuo-relay:before-feishu-$(date +%Y%m%d-%H%M%S)"
docker image tag hainuo-relay:0.1.0 "$backup_tag"
echo "Rollback image: $backup_tag"
docker build --network none --pull=false -f Dockerfile.offline -t hainuo-relay:0.1.0 .
# No App Secret is embedded here, in the image, or in process arguments.
docker run --rm -it --user 0:0 --entrypoint python \
--mount "type=bind,source=$PWD,target=/work" \
hainuo-relay:0.1.0 /work/scripts/configure_feishu_longconn.py --root /work
cat > compose.work.yaml <<'YAML'
services:
connector:
environment:
HN_FEISHU_EVENT_SOURCE: longconn
HN_OAUTH_ENABLED: "false"
HN_REQUEST_TIMEOUT: "180"
longconn:
environment:
HN_FEISHU_EVENT_SOURCE: longconn
YAML
args=(-f compose.yaml -f compose.offline.yaml)
for extra in compose.edge-fix.yaml compose.native-api.yaml compose.h5.yaml; do
if [ -f "$extra" ]; then args+=(-f "$extra"); fi
done
args+=(-f compose.work.yaml)
docker compose "${args[@]}" --profile longconn config --quiet
docker compose "${args[@]}" --profile longconn up -d --no-build --pull never --no-deps --force-recreate connector
for attempt in {1..30}; do
if docker compose "${args[@]}" exec -T connector python -c \
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/ready',timeout=2)" 2>/dev/null; then
docker compose "${args[@]}" --profile longconn up -d --no-build --pull never --no-deps --force-recreate longconn
docker compose "${args[@]}" --profile longconn ps connector longconn
echo 'Next: docker compose logs --tail 30 longconn; look for platform_connected.'
exit 0
fi
sleep 2
done
echo 'Connector not ready; inspect docker compose logs connector. Do not post .env contents.'
exit 1