diff --git a/.DS_Store b/.DS_Store index 6527e68..d79ab94 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/.env.production b/.env.production index f56f7c0..f558fc8 100644 --- a/.env.production +++ b/.env.production @@ -19,7 +19,7 @@ REDIS_MAX_CONNECTIONS=50 # Application Configuration # ====================== # JWT Secret Key (IMPORTANT: Change this in production!) -JWT_SECRET_KEY=cosmo +JWT_SECRET_KEY=cosmo_4f8b9e2a7c1d0f5e6a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f # CORS - Support both internal IP access and external domain # Format: comma-separated list of origins diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index b57de1a..73517ef 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -251,10 +251,34 @@ ls -lh /opt/cosmo/data/backups/ ### 系统更新 ```bash -# 拉取最新代码并重启 +# 拉取最新代码、重建镜像、重启,并同步数据库结构 ./scripts/deploy.sh --update ``` +`--update` 在重启后会执行 `scripts/upgrade_db.py --apply`,把新版本模型里新增的 +**表 / 字段 / 索引**补上(后端启动时的 `create_all()` 只建表,不会给已有表加列)。 +这个脚本只做增量:已有字段、类型、约束和数据都不会被修改或删除。 + +想先看清楚会执行什么 DDL,可以单独跑一次 dry-run(不加 `--apply` 只打印不执行): + +```bash +cd /opt/cosmo +docker-compose exec -T backend python scripts/upgrade_db.py # 预览 +docker-compose exec -T backend python scripts/upgrade_db.py --apply # 执行 +``` + +> **表结构之外的数据不在它的职责范围内**: +> - `system_settings` 的新增配置项由后端启动时自动补齐,无需干预; +> - `rocket_configs` 里的新增火箭型号属于业务数据,需要在管理端重新录入, +> 或者从开发库同步: +> ```bash +> # 开发机导出 +> docker exec -e PGPASSWORD=xxx postgres17 pg_dump -U postgres -d cosmo_db -t rocket_configs > rockets.sql +> # 服务器导入 +> docker-compose cp rockets.sql postgres:/tmp/rockets.sql +> docker-compose exec -T postgres psql -U postgres -d cosmo_db -f /tmp/rockets.sql +> ``` + ### 清理操作 ```bash @@ -308,45 +332,64 @@ docker-compose restart frontend 编辑 `.env.production`: ```bash DATABASE_PASSWORD=strong_random_password_here +JWT_SECRET_KEY=至少32位的随机字符串 # 必填,缺失时 docker-compose 会直接报错退出 ``` +`JWT_SECRET_KEY` 现在会显式注入 backend 容器(`${JWT_SECRET_KEY:?...}`)。 +以前它只存在于 `backend/.env` 里,容器里读不到,于是回落到代码里的默认值—— +所有部署共用同一个密钥,而且每次重启容器用户都会被踢下线。 +缺失时 `docker-compose up` 会报 `JWT_SECRET_KEY is required, set it in .env` 并退出,属于预期行为。 + +> 改了密钥会让现有登录态全部失效,用户需要重新登录。 +> 本地开发不受影响(`backend/.env` 直接生效,不走 compose)。 + ### 2. 配置 HTTPS(推荐) -使用 Let's Encrypt 免费证书: +Nginx 跑在 `cosmo_frontend` 容器里,宿主机上没有 Nginx,所以 **不能用 `certbot --nginx`**; +`nginx.conf` 里 `location ~ /\.` 会拒掉 `/.well-known/acme-challenge/`,webroot 模式也会 403。 +用 standalone 签发: ```bash # 安装 certbot -sudo apt install certbot python3-certbot-nginx +sudo apt install certbot -# 获取证书 -sudo certbot --nginx -d your-domain.com - -# 证书自动续期 -sudo crontab -e -# 添加: 0 3 * * * certbot renew --quiet +# 80 端口被前端容器占着,先停掉再签 +cd /opt/cosmo && docker-compose stop frontend +sudo certbot certonly --standalone -d your-domain.com +docker-compose start frontend ``` -修改 `nginx/nginx.conf` 添加 SSL 配置: +证书在宿主机 `/etc/letsencrypt/`,`docker-compose.yml` 已经把该目录只读挂进前端容器, +并把 443 端口映射出去了。剩下只差取消 `nginx/nginx.conf` 里那三行注释: ```nginx -server { - listen 443 ssl http2; - server_name your-domain.com; - - ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem; - ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem; - - # 其他配置... -} - -# HTTP 重定向到 HTTPS -server { - listen 80; - server_name your-domain.com; - return 301 https://$server_name$request_uri; -} + server { + listen 80; + listen 443 ssl; # 取消注释 + ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem; # 换成你的域名 + ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem; + server_name _; + # ... 后面的 location 原样不动,80 和 443 共用一套 ``` +```bash +cd /opt/cosmo && docker-compose exec frontend nginx -t && docker-compose restart frontend +``` + +证书自动续期(续期时同样要腾出 80 端口,并让容器重新读一次证书): + +```bash +sudo crontab -e +# 0 3 * * * cd /opt/cosmo && docker-compose stop frontend && certbot renew --quiet; docker-compose start frontend +``` + +> **别加 HTTP→HTTPS 的 301。** ESP32 固件用的是裸 `HTTPClient`,不跟跳转:`/api` 一跳转, +> 终端就拿不到数据了。要么终端那边直接把地址填成 `https://your-domain.com/api`, +> 要么让 `/api/` 继续留在 80 上。 +> +> 固件支持 https(`WiFiClientSecure`,不校验证书链,只要链路加密), +> 地址配置见 `terminal/firmware/README.md` 的「后端地址」一节。 + ### 3. 防火墙配置 ```bash diff --git a/backend/app/api/celestial_resource.py b/backend/app/api/celestial_resource.py index 25b8370..448194f 100644 --- a/backend/app/api/celestial_resource.py +++ b/backend/app/api/celestial_resource.py @@ -13,6 +13,7 @@ from sqlalchemy import select, update from pydantic import BaseModel from typing import Optional, Dict, Any +from app.config import settings from app.database import get_db from app.models.db import Resource from app.services.celestial_body_service import celestial_body_service @@ -22,6 +23,26 @@ logger = logging.getLogger(__name__) router = APIRouter(prefix="/celestial/resources", tags=["celestial-resource"]) +# icon 在界面上只有一个槽位(ResourceManager 只渲染 items[0]),换图必须是覆盖语义, +# 否则旧行既看不到也删不掉,resources 表会一直堆积同一张图的替代品。 +# texture / model 是多值列表(每条可单独设 scale),不能套用覆盖。 +SINGLE_VALUE_TYPES = ("icon",) + + +def remove_upload_file(relative_path: str) -> None: + """Delete an uploaded file; a missing file is not an error. + + file_path is stored relative to the upload root ("icon/x.png"), so it has to be + resolved against UPLOAD_DIR first - os.path.exists("icon/x.png") is always False. + """ + path = os.path.join(settings.upload_dir, relative_path) + if os.path.exists(path): + try: + os.remove(path) + logger.info(f"Deleted file: {path}") + except Exception as e: + logger.warning(f"Failed to delete file {path}: {e}") + # Pydantic models class ResourceUpdate(BaseModel): @@ -96,6 +117,22 @@ async def upload_resource( # Determine MIME type mime_type = file.content_type + # Replace previous records of single-value types (files are removed after commit) + replaced_paths: list = [] + if resource_type in SINGLE_VALUE_TYPES: + stale = await db.execute( + select(Resource).where( + Resource.body_id == body_id, + Resource.resource_type == resource_type, + ) + ) + for old in stale.scalars().all(): + replaced_paths.append(old.file_path) + await db.delete(old) + # Flush the deletes first: the unit of work would insert before deleting + # and trip the (body_id, resource_type, file_path) unique index. + await db.flush() + # Create resource record resource = await resource_service.create_resource( { @@ -112,6 +149,10 @@ async def upload_resource( await db.commit() await db.refresh(resource) + for stale_path in replaced_paths: + if stale_path != relative_path: # same-second re-upload reuses the path + remove_upload_file(stale_path) + logger.info(f"Uploaded resource for {body.name} ({body.type}): {relative_path} ({file_size} bytes)") return { @@ -178,12 +219,7 @@ async def delete_resource( # Delete file if it exists file_path = resource.file_path - if os.path.exists(file_path): - try: - os.remove(file_path) - logger.info(f"Deleted file: {file_path}") - except Exception as e: - logger.warning(f"Failed to delete file {file_path}: {e}") + remove_upload_file(file_path) # Delete database record deleted = await resource_service.delete_resource(resource_id, db) diff --git a/docker-compose.yml b/docker-compose.yml index d10aaf4..5d77d35 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -61,23 +61,27 @@ services: DATABASE_NAME: ${DATABASE_NAME:-cosmo_db} DATABASE_USER: ${DATABASE_USER:-postgres} DATABASE_PASSWORD: ${DATABASE_PASSWORD:-postgres} - DATABASE_POOL_SIZE: 20 - DATABASE_MAX_OVERFLOW: 10 + DATABASE_POOL_SIZE: ${DATABASE_POOL_SIZE:-20} + DATABASE_MAX_OVERFLOW: ${DATABASE_MAX_OVERFLOW:-10} # Redis REDIS_HOST: redis REDIS_PORT: 6379 REDIS_DB: 0 REDIS_PASSWORD: ${REDIS_PASSWORD:-} - REDIS_MAX_CONNECTIONS: 50 + REDIS_MAX_CONNECTIONS: ${REDIS_MAX_CONNECTIONS:-50} # Application APP_NAME: "Cosmo - Deep Space Explorer" API_PREFIX: /api + # backend/.env is excluded by backend/.dockerignore, so this has to come from here. + # Without it the app silently signs every token with the hard-coded dev default, + # which lets anyone forge user / terminal tokens. Fail fast instead of guessing. + JWT_SECRET_KEY: ${JWT_SECRET_KEY:?JWT_SECRET_KEY is required, set it in .env} CORS_ORIGINS: ${CORS_ORIGINS:-http://localhost} # Cache - CACHE_TTL_DAYS: 3 + CACHE_TTL_DAYS: ${CACHE_TTL_DAYS:-3} # Upload UPLOAD_DIR: /app/upload - MAX_UPLOAD_SIZE: 10485760 + MAX_UPLOAD_SIZE: ${MAX_UPLOAD_SIZE:-10485760} # Proxy (for accessing NASA JPL Horizons API) HTTP_PROXY: ${HTTP_PROXY:-} HTTPS_PROXY: ${HTTPS_PROXY:-} @@ -113,8 +117,11 @@ services: restart: unless-stopped volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro + # certbot 在宿主机上签发的证书,nginx 容器里要能读到(启用 443 时需要) + - /etc/letsencrypt:/etc/letsencrypt:ro ports: - "80:80" + - "443:443" depends_on: - backend networks: diff --git a/nginx/nginx.conf b/nginx/nginx.conf index 0b3fc5b..5c949a2 100644 --- a/nginx/nginx.conf +++ b/nginx/nginx.conf @@ -40,8 +40,14 @@ http { keepalive 32; } + # One server block serves both plain HTTP and HTTPS, so enabling TLS is just + # uncommenting the three lines below (see DEPLOYMENT.md 配置 HTTPS). server { listen 80; + #listen 443 ssl; # 同一个 server 兼容 80/443 + #ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem; + #ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem; + # 证书目录已由 docker-compose 只读挂载进容器 server_name _; # Root directory for static files diff --git a/scripts/deploy.sh b/scripts/deploy.sh index 16114ea..ac3c42d 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -247,6 +247,13 @@ update_system() { # Restart services docker-compose up -d + # Schema sync: the backend only runs create_all() on boot, which creates missing + # tables but never adds columns to tables that already exist. + log "Upgrading database schema (additive only)..." + docker-compose exec -T backend mkdir -p /app/scripts + docker-compose cp scripts/upgrade_db.py backend:/app/scripts/upgrade_db.py + docker-compose exec -T backend python scripts/upgrade_db.py --apply + log "✓ System updated" } diff --git a/scripts/upgrade_db.py b/scripts/upgrade_db.py new file mode 100644 index 0000000..be3b7bd --- /dev/null +++ b/scripts/upgrade_db.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +""" +Schema upgrade script for an existing Cosmo database. + +The backend runs `Base.metadata.create_all()` on every boot, which creates tables +added since the first deploy but never touches tables that already exist. Columns +added to the ORM models afterwards stay missing on the server. This script diffs the +ORM metadata against the live database and applies what is missing: + + - missing tables (with their indexes and constraints, via create_all) + - missing columns on existing tables (ADD COLUMN IF NOT EXISTS) + - missing indexes on existing tables (CREATE INDEX IF NOT EXISTS) + +It is additive only: existing columns, types, constraints and data are never changed +or dropped. Data (new rocket models, system settings, ...) is out of scope here. + +Usage: + python scripts/upgrade_db.py # dry run, print the DDL + python scripts/upgrade_db.py --apply # execute it +""" +import asyncio +import logging +import os +import sys +from pathlib import Path + +# Runs from the repo (/scripts, app code in /backend) and from +# inside the backend image (deploy.sh copies it to /app/scripts, app code in /app). +BACKEND_DIR = Path(__file__).resolve().parent.parent / "backend" +if not (BACKEND_DIR / "app").is_dir(): + BACKEND_DIR = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(BACKEND_DIR)) +os.chdir(BACKEND_DIR) + +from sqlalchemy import inspect, text +from sqlalchemy.schema import CreateIndex, CreateTable + +from app.database import engine, Base +from app.config import settings +import app.models.db # noqa: F401 (register every model on Base.metadata) + +logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s") +logger = logging.getLogger(__name__) + + +def column_stmt(table_name: str, col, dialect, strict: bool) -> str: + """ALTER TABLE ... ADD COLUMN for one missing column. + + strict=False drops NOT NULL, used as fallback when the table already has rows + and the model gives no default Postgres could fill in. + """ + sql = (f'ALTER TABLE "{table_name}" ADD COLUMN IF NOT EXISTS "{col.name}" ' + f'{col.type.compile(dialect=dialect)}') + if strict and not col.nullable: + sql += " NOT NULL" + default = col.server_default.arg if col.server_default is not None else None + if default is None and col.default is not None and not col.default.is_callable: + default = col.default.arg + if hasattr(default, "compile"): # func.now() and friends + sql += " DEFAULT CURRENT_TIMESTAMP" + elif isinstance(default, str): + sql += " DEFAULT '" + default.replace("'", "''") + "'" + elif isinstance(default, bool): + sql += " DEFAULT " + ("TRUE" if default else "FALSE") + elif default is not None: + sql += f" DEFAULT {default}" + return sql + + +def diff(conn): + """Compare ORM metadata with the live schema; returns (changes, notes).""" + live = inspect(conn) + tables = live.get_table_names() + if not tables: + return [], ["空库:后端首次启动会自己建全部表,无需本脚本。"] + + changes, notes = [], [] + for name, table in Base.metadata.tables.items(): + if name not in tables: + changes.append({"kind": "table", "label": name, + "sql": str(CreateTable(table).compile(dialect=conn.dialect))}) + continue + + existing = {c["name"] for c in live.get_columns(name)} + for col in table.columns: + if col.name in existing: + continue + changes.append({ + "kind": "column", "label": f"{name}.{col.name}", + "sql": column_stmt(name, col, conn.dialect, strict=True), + "fallback": column_stmt(name, col, conn.dialect, strict=False), + }) + + pk_cols = {c.name for c in table.primary_key} + # Compare by covered columns, not only by name: the hand-written init_db.sql + # names indexes idx_*, the ORM declares ix_*, so a name-only check wants to + # add a duplicate index over identical columns on every existing database. + covered = set() + for item in live.get_indexes(name): + if item.get("column_names"): + covered.add((tuple(item["column_names"]), bool(item.get("unique")))) + for item in live.get_unique_constraints(name): + if item.get("column_names"): + covered.add((tuple(item["column_names"]), True)) + live_names = {i["name"] for i in live.get_indexes(name)} + for index in table.indexes: + cols = tuple(c.name for c in index.columns) + if set(cols) <= pk_cols: + continue # the primary key already covers single-PK indexes + if index.name in live_names or (cols, bool(index.unique)) in covered: + continue # same columns already indexed (unique constraint counts) + sql = str(CreateIndex(index, if_not_exists=True).compile(dialect=conn.dialect)) + changes.append({"kind": "index", "label": index.name, "sql": sql}) + + # Missing foreign keys on existing tables are reported, not applied: they can + # fail on orphan rows and silently lock out writes. + for name, table in Base.metadata.tables.items(): + if name not in tables: + continue + live_fk_cols = {c for fk in live.get_foreign_keys(name) for c in fk["constrained_columns"]} + for fk in table.foreign_keys: + if fk.parent.name not in live_fk_cols: + notes.append(f"{name}: 缺少外键 {fk.parent.name} -> {fk.target_fullname}" + f"(脚本不加外键,确认数据干净后手工执行)") + return changes, notes + + +async def main(apply: bool): + logger.info(f"Database: {settings.database_url.split('@')[-1]}") + + async with engine.connect() as conn: + changes, notes = await conn.run_sync(diff) + + for change in changes: + logger.info(f"[{change['kind']}] {change['label']}") + logger.info(" " + " ".join(change["sql"].split())) + if not changes: + logger.info("✓ Schema is up to date, nothing to do") + for note in notes: + logger.warning(f"! {note}") + + if not changes or not apply: + if changes: + logger.info("Dry run only. Re-run with --apply to execute.") + return + + async with engine.begin() as conn: + for change in changes: + try: + # SAVEPOINT per statement: one failure must not abort the whole upgrade. + async with conn.begin_nested(): + if change["kind"] == "table": + await conn.run_sync(lambda c, t=change["label"]: Base.metadata.create_all( + c, tables=[Base.metadata.tables[t]], checkfirst=True)) + else: + await conn.execute(text(change["sql"])) + logger.info(f"✓ {change['kind']} {change['label']} applied") + except Exception as e: + if change["kind"] != "column": + raise + async with conn.begin_nested(): + await conn.execute(text(change["fallback"])) + logger.warning(f"! {change['label']}: 已按 NULL 建列(原表有数据,NOT NULL 填不出默认值)," + f"请回填后再收紧 ({e})") + + logger.info("✓ Schema upgrade finished") + + +if __name__ == "__main__": + asyncio.run(main("--apply" in sys.argv)) diff --git a/terminal/firmware/README.md b/terminal/firmware/README.md index 5ae7330..ef3b1ec 100644 --- a/terminal/firmware/README.md +++ b/terminal/firmware/README.md @@ -120,9 +120,10 @@ FQBN='esp32:esp32:esp32s3:PSRAM=opi,FlashSize=16M,FlashMode=dio,CDCOnBoot=defaul - **版本门控**:`/api/terminal/follows` 每个天体多返回一个 `icon_ver`(= 图标资源行的 id, 也是图标端点的 `ETag`)。固件只在 `icon_ver` 变化时下载,稳态零流量;实测一个天体 拉 40+64 两张 ~130ms。 -- **一个天体维护了多张图标**时后端取**最新**(`created_at desc, id desc`)。 - ⚠️ 管理端 `ResourceManager.tsx` 的预览和删除用的是 `items[0]`(`created_at` **最旧**那条), - 重复上传时两边指向的不是同一行,换完图要对一下 `stat` 里的版本号。 +- **换图是覆盖语义**:同一个天体同一种资源类型只保留一行,重复上传时后端删掉旧行 + 并删掉旧文件(`app/api/celestial_resource.py`)。终端只在 `icon_ver` 变化时重下, + 管理端预览/删除的 `items[0]` 和后端取的那一行从此指向同一张图。 + (只有 `icon` 是覆盖;`texture` / `model` 是多值列表,追加语义保持不变。) - **固件缓存** `src/iconstore.{h,cpp}`:一个关注天体一个槽(上限 `MAX_BODIES=6`), 点阵 `heap_caps_malloc(MALLOC_CAP_SPIRAM|MALLOC_CAP_8BIT)` 惰性分配,每槽 3200+8192=11392B,最坏 6 槽约 68KB PSRAM;取消关注的槽在下次 sync 时释放(缓冲区留着复用)。 @@ -156,6 +157,41 @@ curl --noproxy '*' -H "Authorization: Bearer $TOK" -o /tmp/ic_599_40.bin \ 凭据、后端地址、token 都存在 NVS 命名空间 `cosmo`。 +### 后端地址(换服务器 / 上 https 只看这一节) + +地址存 NVS 键 `api`,**只有 NVS 里还没有这个键时**才用编译期的默认值: + +```c +// cosmo_terminal.ino:26 +#define DEFAULT_API "http://192.168.31.2:8000/api" +``` + +换正式地址有三种改法,前两种不用重新烧录: + +| 改法 | 怎么做 | 适用 | +| --- | --- | --- | +| 串口 | `api https://your-domain.com/api`(写 NVS,立刻重新取数) | 设备在手边,最快 | +| 配网页 | 串口 `portal` 或首次开机 → `http://192.168.4.1` → 后端地址 | 没有串口线 | +| 重烧 | 改 `cosmo_terminal.ino:26` 的 `DEFAULT_API` 再编译烧录;**只有 NVS 里没有 `api` 键的设备**才会读到它 | 批量出厂 | + +> 重烧固件**不清 NVS**:已经配过网/敲过 `api` 的设备,改了 `DEFAULT_API` 也还是旧地址。 +> 要么串口 `api <新地址>` 覆盖一次,要么串口 `reset` 清空整个 NVS(连 WiFi 凭据和 token +> 一起清,设备会回到配网+配对流程),让它重新回落到 `DEFAULT_API`。 +> 配网页现在预填**当前生效的地址**(以前预填 `DEFAULT_API`,重开配网页直接点保存 +> 会把地址刷回编译期那个局域网 IP)。 + +`http://` 和 `https://` 都支持:`src/api.cpp:tls_make()` 按前缀分流,`https://` 走 +`WiFiClientSecure`(`setHandshakeTimeout(10)`),其余走裸 `HTTPClient`。 + +- **不校验证书链**(`setInsecure()`):只要链路加密。代价是理论上可被中间人, + 收益是换 CA / 证书续期都不用重烧固件。要严格校验就把 `setInsecure()` 换成 + `setCACert(root_ca)`,代价是根证书编进固件、换 CA 必须重烧。 +- TLS 握手瞬时要多占几十 KB 堆(`WiFiClientSecure` 的 mbedTLS 上下文)。这块板子是 + OPI PSRAM、堆本来就宽,编译后 RAM 仍在 16% 左右,但这条只在编译层面验证过, + 上正式 https 服务后建议串口 `stat` 看一眼剩余堆。 +- **别把服务器配成 HTTP→HTTPS 的 301**:`HTTPClient` 不跟跳转,终端会直接拿不到数据。 + 要么地址直接填 `https://`,要么让 `/api/` 继续留在 80 上。 + ## 绑定与取数 ``` diff --git a/terminal/firmware/cosmo_terminal/cosmo_terminal.ino b/terminal/firmware/cosmo_terminal/cosmo_terminal.ino index f46a379..bdcc12b 100644 --- a/terminal/firmware/cosmo_terminal/cosmo_terminal.ino +++ b/terminal/firmware/cosmo_terminal/cosmo_terminal.ino @@ -93,7 +93,9 @@ static void build_identity() /* ---------------- 配网 ---------------- */ static void start_provision() { - portal_start(g_ap_ssid, DEFAULT_API); + /* 预填 NVS 里当前生效的地址:填 DEFAULT_API 的话,重开配网页直接点保存 + 会把后端地址刷回编译期那个局域网 IP */ + portal_start(g_ap_ssid, g_ui.api); g_ui.wifi_up = false; /* 配网时 STA 已断开,状态栏不能再显示 NET:ONLINE */ set_screen(SC_PROVISION); Serial.printf("[portal] AP=%s -> http://192.168.4.1\n", g_ap_ssid); diff --git a/terminal/firmware/cosmo_terminal/src/api.cpp b/terminal/firmware/cosmo_terminal/src/api.cpp index 48a8c5b..0ae9fed 100644 --- a/terminal/firmware/cosmo_terminal/src/api.cpp +++ b/terminal/firmware/cosmo_terminal/src/api.cpp @@ -1,10 +1,33 @@ #include #include #include +#include +#include #include #include "api.h" +/* https 用 TLS,但不校验证书链(setInsecure):要的是链路加密,不是身份认证。 + 板子自带的根证书包一换签发机构(Let's Encrypt 换 CA)就得重烧固件,中间证书 + 轮换也会连不上。要严格校验,把根证书 PEM 编进固件再改成 setCACert(root_ca)。 */ +static std::unique_ptr tls_make(const char *url) +{ + if (strncmp(url, "https://", 8) != 0) return nullptr; + auto tls = std::make_unique(); + tls->setInsecure(); + tls->setHandshakeTimeout(10); /* 秒;TLS 握手比 HTTP 更容易卡住 */ + return tls; +} + +/* HTTPClient 只是借用这个 client,但 ~HTTPClient() 无条件 _client->stop(),而 end() + 在连接已断开或 keep-alive 复用时不会把 _client 置空。所以 tls 必须在 HTTPClient + 之前声明(局部变量逆序析构 = tls 比 http 活得久),否则析构时踩已释放的 client。 */ +static void http_begin(HTTPClient &http, const char *url, const std::unique_ptr &tls) +{ + if (tls) http.begin(*tls, url); + else http.begin(url); +} + /* 中文标题被过滤空了就用 event_type 兜底:"close_approach" -> "CLOSE APPROACH" */ static void copy_upper(char *dst, size_t cap, const char *src) { @@ -63,10 +86,11 @@ static void copy_title(char *dst, size_t cap, const char *src) static bool http_json(const char *url, const char *body, const char *token, JsonDocument &doc, int *status) { + auto tls = tls_make(url); /* 声明在 http 之前,见 http_begin 注释 */ HTTPClient http; http.setConnectTimeout(6000); http.setTimeout(8000); - http.begin(url); + http_begin(http, url, tls); http.addHeader("Content-Type", "application/json"); if (token && *token) http.addHeader("Authorization", String("Bearer ") + token); int code = body ? http.POST(body) : http.GET(); @@ -192,10 +216,11 @@ bool api_icon(const char *base, const char *token, const char *body_id, int size void *dst, size_t cap, int *http_status) { String url = String(base) + "/terminal/bodies/" + body_id + "/icon?size=" + size; + auto tls = tls_make(url.c_str()); /* 声明在 http 之前,见 http_begin 注释 */ HTTPClient http; http.setConnectTimeout(6000); http.setTimeout(8000); - http.begin(url); + http_begin(http, url.c_str(), tls); if (token && *token) http.addHeader("Authorization", String("Bearer ") + token); int code = http.GET(); if (http_status) *http_status = code;