diff --git a/AGENTS.md b/AGENTS.md index 1144aff..cab42fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,6 +9,9 @@ This file is the only mandatory entry point for AI-assisted work in this reposit ## Project and safety baseline - Target: ESP32-C3, 8 MB Flash, no PSRAM, ESP-IDF 5.5.3. +- Preserve mini-program BLE install compatibility: the 3 MB application limit, + `cardid` at `0x356000`, permanent Recovery at `0x700000`, and the five-second + UP-key bootloader hook are mandatory template contracts. - Preserve existing user changes. Start with `git status --short --branch`; never overwrite or clean unrelated files. - Hardware facts follow this priority: product specifications and measured results → `components/bsp/include/bsp_pins.h` → BSP headers and implementation → hardware guide → README/demo code. If a task requires a hardware detail not defined by these sources, ask the user instead of guessing. - Reusable board logic belongs in `components/bsp`; pages, state machines, animations, and application tasks belong in `main`. @@ -27,7 +30,7 @@ This file is the only mandatory entry point for AI-assisted work in this reposit | Environment bootstrap or missing toolchain | `docs/development/environment-setup.md` | | BSP, pins, buses, display, audio, battery | `docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md`, `components/bsp/include/bsp_pins.h` | | Demo or menu | `main/demo.h`, `main/main.c`, the nearest `main/demo_*.c` implementation | -| Build, test, dependencies, partitions | `docs/development/build-and-test.md`, `sdkconfig.defaults`, `partitions.csv` | +| Build, test, dependencies, partitions | `docs/development/build-and-test.md`, `docs/development/ble-recovery-compatibility.md`, `sdkconfig.defaults`, `partitions.csv` | | CI or release | the matching file in `docs/development/CI-*.md` and `.github/workflows/` | | Post-release follow-up | `docs/development/after-release.md` (then the `issue-suggestions` or `experience-pr` skill) | | Documentation | `docs/contribution/doc-conventions.md`, `docs/INDEX.md` | diff --git a/AGENTS.zh_CN.md b/AGENTS.zh_CN.md index 7d5d21e..8640991 100644 --- a/AGENTS.zh_CN.md +++ b/AGENTS.zh_CN.md @@ -9,6 +9,9 @@ ## 项目与安全基线 - 目标平台:ESP32-C3、8 MB Flash、无 PSRAM、ESP-IDF 5.5.3。 +- 必须保持小程序 BLE 安装兼容:3 MB 应用上限、`cardid@0x356000`、 + 永久 `recovery@0x700000` 以及上键持续 5 秒进入 Recovery 的 bootloader hook + 均为模板强制契约。 - 保留用户已有修改。先执行 `git status --short --branch`,不得覆盖或清理无关文件。 - 硬件事实优先级:产品规格与实测结果 → `components/bsp/include/bsp_pins.h` → BSP 头文件与实现 → 硬件指南 → README/demo。任务所需硬件细节未在这些来源中定义时,直接询问用户,不得猜测。 - 可复用板级逻辑放入 `components/bsp`;页面、状态机、动画和应用任务放入 `main`。 @@ -27,7 +30,7 @@ | 环境引导或缺少工具链 | `docs/development/environment-setup.zh_CN.md` | | BSP、引脚、总线、显示、音频、电池 | `docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md`、`components/bsp/include/bsp_pins.h` | | Demo 或菜单 | `main/demo.h`、`main/main.c`、最近的 `main/demo_*.c` 实现 | -| 构建、测试、依赖、分区 | `docs/development/build-and-test.zh_CN.md`、`sdkconfig.defaults`、`partitions.csv` | +| 构建、测试、依赖、分区 | `docs/development/build-and-test.zh_CN.md`、`docs/development/ble-recovery-compatibility.zh_CN.md`、`sdkconfig.defaults`、`partitions.csv` | | CI 或发布 | `docs/development/CI-*.zh_CN.md` 中的对应文件与 `.github/workflows/` | | 发布后收尾 | `docs/development/after-release.zh_CN.md`(再进入 `issue-suggestions` 或 `experience-pr` skill) | | 文档 | `docs/contribution/doc-conventions.zh_CN.md`、`docs/INDEX.zh_CN.md` | diff --git a/CMakeLists.txt b/CMakeLists.txt index c35c2cb..63a15ad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,3 +1,12 @@ cmake_minimum_required(VERSION 3.16) include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +# Community firmware replaces the bootloader when installed over USB. Keep the +# factory Recovery entry gesture in every derivative build so USB development +# does not strand the device outside the mini-program BLE install path. +idf_build_set_property( + BOOTLOADER_EXTRA_COMPONENT_DIRS + "${CMAKE_CURRENT_LIST_DIR}/bootloader_components/" + APPEND) + project(FoloToy-AI-Passport) diff --git a/bootloader_components/recovery_boot_hook/CMakeLists.txt b/bootloader_components/recovery_boot_hook/CMakeLists.txt new file mode 100644 index 0000000..f23a6a5 --- /dev/null +++ b/bootloader_components/recovery_boot_hook/CMakeLists.txt @@ -0,0 +1,5 @@ +idf_component_register( + SRCS "recovery_boot_hook.c" + PRIV_REQUIRES bootloader_support + PRIV_INCLUDE_DIRS "$ENV{IDF_PATH}/components/bootloader_support/private_include" +) diff --git a/bootloader_components/recovery_boot_hook/recovery_boot_hook.c b/bootloader_components/recovery_boot_hook/recovery_boot_hook.c new file mode 100644 index 0000000..01ecdbe --- /dev/null +++ b/bootloader_components/recovery_boot_hook/recovery_boot_hook.c @@ -0,0 +1,31 @@ +// Bootloader hook shared by every AI Passport community firmware derivative. +// Holding the UP-key ADC GPIO low for five seconds boots the factory-installed +// permanent Recovery image. This project never owns or writes that image. +#include "bootloader_common.h" +#include "bootloader_config.h" +#include "bootloader_utility.h" +#include "esp_log.h" + +#define RECOVERY_BUTTON_GPIO 0 +#define RECOVERY_HOLD_SECONDS 5 +#define RECOVERY_OFFSET 0x700000 +#define RECOVERY_SIZE 0x100000 + +void bootloader_hooks_include(void) +{ +} + +void bootloader_after_init(void) +{ + if (bootloader_common_check_long_hold_gpio( + RECOVERY_BUTTON_GPIO, RECOVERY_HOLD_SECONDS) != GPIO_LONG_HOLD) { + return; + } + + ESP_LOGI("recovery_boot", "UP held: booting permanent recovery at 0x%x", + RECOVERY_OFFSET); + bootloader_state_t state = { 0 }; + state.factory.offset = RECOVERY_OFFSET; + state.factory.size = RECOVERY_SIZE; + bootloader_utility_load_boot_image(&state, FACTORY_INDEX); +} diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8b46b99..7e9e73a 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6,6 +6,10 @@ ## Unreleased +- Made mini-program BLE install compatibility a template-level invariant: fixed + protected `cardid`/Recovery partitions, retained the five-second UP-key + Recovery boot hook, and added CI validation for merged-image structure, + partition MD5/ranges, the 3 MB app limit, and protected payload exclusion. - Documented a release-title convention for multi-app releases: name tags as `v-` (e.g. `v0.1.0-voice-keychain`) so the release title carries the version and the app, and confirm the title after the release is published so a release list is scannable by app. - Added a post-release follow-up workflow: an `issue-suggestions` skill for filing user feedback as issues against the upstream project, an `experience-pr` skill for submitting reusable development experience as a documentation PR, a `docs/experiences/` directory for per-entry experience files, and supporting `after-release`, `file-issues`, and experience-index documents. - Simplified the tracked repository root: moved GitHub-recognized community documents into `.github/`, moved the changelog into `docs/`, updated every reference, and added a root-document allowlist to repository checks. diff --git a/docs/CHANGELOG.zh_CN.md b/docs/CHANGELOG.zh_CN.md index 3d9c461..51322cf 100644 --- a/docs/CHANGELOG.zh_CN.md +++ b/docs/CHANGELOG.zh_CN.md @@ -6,6 +6,9 @@ ## Unreleased +- 将小程序 BLE 安装兼容提升为二创模板强制契约:固定保护 `cardid`/Recovery 分区, + 保留上键持续 5 秒进入 Recovery 的 bootloader hook,并在 CI 强制校验合并镜像结构、 + 分区表 MD5/范围、3 MB 应用上限和保护分区数据不入包。 - 规定多应用发布的 Release 标题约定:tag 按 `v<版本>-<应用名>`(如 `v0.1.0-voice-keychain`)命名,让 Release 标题同时带版本与应用名;发布成功后核对标题,保证一眼扫 Release 列表就能区分是哪个应用。 - 新增发布后收尾流程:`issue-suggestions` skill 用于把用户反馈作为 issue 提交到上游项目;`experience-pr` skill 用于把可复用的开发经验作为文档 PR 提交;新增 `docs/experiences/` 目录保存单条经验文件;并配套 `after-release`、`file-issues` 与经验索引文档。 - 精简仓库根目录:将 GitHub 可识别的社区治理文档迁入 `.github/`,将变更记录迁入 `docs/`,同步全部引用,并在仓库检查中加入根目录文档白名单。 diff --git a/docs/INDEX.md b/docs/INDEX.md index eba564c..a909149 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -18,6 +18,7 @@ Use this page to discover repository documentation. `authoritative` documents de | [development/agent-guide.md](development/agent-guide.md) | AI-assisted development workflow | authoritative | | [development/environment-setup.md](development/environment-setup.md) | Clean-machine environment bootstrap for AI agents | authoritative | | [development/build-and-test.md](development/build-and-test.md) | Build and validation commands | authoritative | +| [development/ble-recovery-compatibility.md](development/ble-recovery-compatibility.md) | Mini-program BLE firmware compatibility contract | authoritative | | [development/coding-conventions.md](development/coding-conventions.md) | C and firmware conventions | authoritative | | [development/CI-validation.md](development/CI-validation.md) | Pull-request and main-branch validation | authoritative | | [development/CI-build-and-release.md](development/CI-build-and-release.md) | Tagged firmware builds and releases | authoritative | diff --git a/docs/INDEX.zh_CN.md b/docs/INDEX.zh_CN.md index 89796c3..3cc699f 100644 --- a/docs/INDEX.zh_CN.md +++ b/docs/INDEX.zh_CN.md @@ -18,6 +18,7 @@ | [development/README.zh_CN.md](./development/README.zh_CN.md) | 工程规范索引 | authoritative | 通用工程开发规范(构建验证、代码约定) | | [development/environment-setup.zh_CN.md](./development/environment-setup.zh_CN.md) | 工程规范 | authoritative | AI 全新机器环境引导、国际与中国大陆下载线路 | | [development/build-and-test.zh_CN.md](./development/build-and-test.zh_CN.md) | 工程规范 | authoritative | 构建与验证(ESP-IDF 命令、逻辑测试、改动验证要求) | +| [development/ble-recovery-compatibility.zh_CN.md](./development/ble-recovery-compatibility.zh_CN.md) | 工程规范 | authoritative | 小程序 BLE 固件产物、分区与 bootloader 兼容契约 | | [development/coding-conventions.zh_CN.md](./development/coding-conventions.zh_CN.md) | 工程规范 | authoritative | 代码约定(语言风格、复用、注释、测试同步、资源约束) | | [development/agent-guide.zh_CN.md](./development/agent-guide.zh_CN.md) | 工程规范 | authoritative | AI 开发工作流(上下文建立、需求拆解、BSP 边界、验收交付格式) | | [development/CI-build-and-release.zh_CN.md](./development/CI-build-and-release.zh_CN.md) | CI 文档 | authoritative | 自动构建与发布说明(tag 触发自动编译固件并发布 Release) | diff --git a/docs/README.md b/docs/README.md index 744ad68..098c161 100644 --- a/docs/README.md +++ b/docs/README.md @@ -30,7 +30,7 @@ The table below describes the application capabilities implemented by the curren All pins, addresses, panel parameters, and button voltage windows are defined only in [`components/bsp/include/bsp_pins.h`](../components/bsp/include/bsp_pins.h). Application code must not duplicate these constants. See the [AI Hardware Development Guide](hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md) for the complete pin map, panel initialization, ADC thresholds, I2C addressing rules, audio clocks, and memory details. -Applications may also use ESP-IDF timers, FreeRTOS tasks, and internal Flash/NVS; the Pomodoro branch contains an NVS example. Wi-Fi and Bluetooth LE remain ESP-IDF application services rather than BSP APIs: their menu pages initialize each stack only while open and release it on exit. `demo/claude-buddy-port` remains a fuller BLE application architecture reference, not a substitute for measuring the current board's antenna, RF performance, power consumption, and coexistence behavior. The current product and firmware baseline uses 8 MB Flash with a 3 MB factory-app partition. +Applications may also use ESP-IDF timers, FreeRTOS tasks, and internal Flash/NVS; the Pomodoro branch contains an NVS example. Wi-Fi and Bluetooth LE remain ESP-IDF application services rather than BSP APIs: their menu pages initialize each stack only while open and release it on exit. `demo/claude-buddy-port` remains a fuller BLE application architecture reference, not a substitute for measuring the current board's antenna, RF performance, power consumption, and coexistence behavior. The current product and firmware baseline uses 8 MB Flash with a 3 MB factory-app partition plus fixed protected identity and permanent-Recovery regions so derivative firmware stays installable through the mini-program. ### Capabilities outside the current contract @@ -104,7 +104,7 @@ tools/ Shared local/CI validation and firmware verification sc docs/ Project docs, changelog, engineering/contribution rules, and design references .github/ GitHub community files, PR template, issue forms, and CI workflows sdkconfig.defaults ESP32-C3, USB console, Flash, and LVGL defaults -partitions.csv NVS, PHY data, and 3 MB factory application layout +partitions.csv App plus protected identity/Recovery layout dependencies.lock Reproducible ESP-IDF Managed Component resolution AGENTS.md Mandatory AI-agent entry point (paired with AGENTS.zh_CN.md) CLAUDE.md Claude Code pointer to AGENTS.md (paired Chinese version) diff --git a/docs/README.zh_CN.md b/docs/README.zh_CN.md index 511ca9b..4475ef8 100644 --- a/docs/README.zh_CN.md +++ b/docs/README.zh_CN.md @@ -30,7 +30,7 @@ FoloToy AI Passport 是一个开放式可穿戴 AI 硬件,本仓库是这款 A 所有引脚、地址、面板参数和按键电压窗口只在 [`components/bsp/include/bsp_pins.h`](../components/bsp/include/bsp_pins.h) 定义。应用代码不得复制这些常量。完整引脚表、面板初始化、ADC 阈值、I2C 地址规则、音频时钟和内存说明见 [AI 硬件开发指南](hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md)。 -应用也可以使用 ESP-IDF 提供的定时器、FreeRTOS 任务和内部 Flash/NVS;番茄钟分支提供了 NVS 示例。Wi-Fi 和 Bluetooth LE 仍是 ESP-IDF 应用服务而非 BSP API:其菜单页面仅在打开时初始化对应协议栈、退出时释放。`demo/claude-buddy-port` 仍是更完整的 BLE 应用架构参考,不能替代对当前板卡天线、射频表现、功耗和共存行为的实测。当前产品与固件基线使用 8 MB Flash,并包含 3 MB factory-app 分区。 +应用也可以使用 ESP-IDF 提供的定时器、FreeRTOS 任务和内部 Flash/NVS;番茄钟分支提供了 NVS 示例。Wi-Fi 和 Bluetooth LE 仍是 ESP-IDF 应用服务而非 BSP API:其菜单页面仅在打开时初始化对应协议栈、退出时释放。`demo/claude-buddy-port` 仍是更完整的 BLE 应用架构参考,不能替代对当前板卡天线、射频表现、功耗和共存行为的实测。当前产品与固件基线使用 8 MB Flash,包含 3 MB factory-app 分区,并固定保留设备身份与永久 Recovery 区域,使二创固件仍可通过小程序安装。 ### 不属于当前能力契约的事项 @@ -103,7 +103,7 @@ tools/ 本地与 CI 共用的验证及固件校验脚本 docs/ 项目说明、变更记录、工程/协作规范与设计参考 .github/ GitHub 社区文档、PR 模板、Issue Form 与 CI 工作流 sdkconfig.defaults ESP32-C3、USB console、Flash、LVGL 默认配置 -partitions.csv NVS、PHY data 与 3 MB factory-app 分区布局 +partitions.csv 应用与设备身份/Recovery 保护分区布局 dependencies.lock 可复现的 ESP-IDF Managed Component 解析结果 AGENTS.md AI agent 必读入口(与 AGENTS.zh_CN.md 配对) CLAUDE.md Claude Code 指向 AGENTS.md 的入口(含中文配对) diff --git a/docs/development/CI-build-and-release.md b/docs/development/CI-build-and-release.md index 153ef3d..10b4d0d 100644 --- a/docs/development/CI-build-and-release.md +++ b/docs/development/CI-build-and-release.md @@ -6,7 +6,7 @@ `.github/workflows/build-firmware.yml` builds and publishes firmware for tags and supports manual dispatch. Ordinary branch pushes do not trigger it. Keep this page synchronized with the workflow. -The build job restores ccache, runs `./tools/validate.sh --firmware` with ESP-IDF 5.5.3 for ESP32-C3, verifies the bootloader at `0x0`, partition table at `0x8000`, application at `0x10000`, and 8 MB Flash arguments, then uploads `FoloToy-AI-Passport-full.bin`. A separate least-privilege release job publishes that artifact only for a tag. +The build job restores ccache, runs `./tools/validate.sh --firmware` with ESP-IDF 5.5.3 for ESP32-C3, verifies the bootloader at `0x0`, partition table at `0x8000`, application at `0x10000`, 8 MB Flash arguments, and the complete mini-program BLE compatibility contract, then uploads `FoloToy-AI-Passport-full.bin`. A separate least-privilege release job publishes that artifact only for a tag. All Actions are pinned to full commit SHAs. The build job has `contents: read`; only the tag release job receives `contents: write`. @@ -62,4 +62,3 @@ consistent with `docs/CHANGELOG.md` for user-visible behavior. - Firmware publishing to the community: [publish-to-community.md](publish-to-community.md) - Post-release follow-up: [after-release.md](after-release.md) - diff --git a/docs/development/CI-build-and-release.zh_CN.md b/docs/development/CI-build-and-release.zh_CN.md index c03073d..952d0fb 100644 --- a/docs/development/CI-build-and-release.zh_CN.md +++ b/docs/development/CI-build-and-release.zh_CN.md @@ -19,7 +19,7 @@ 1. **ccache 缓存恢复**:使用 `actions/cache` 缓存编译中间产物(`.ccache`),二次编译大幅提速。缓存 key 含 ref 与 commit SHA;缓存保留时间以仓库的 GitHub Actions 设置为准。 2. **编译与验证**(ESP-IDF 5.5.3 / esp32c3):运行与本地相同的 `./tools/validate.sh --firmware`。脚本使用 `sdkconfig.defaults` 和 `partitions.csv` 构建固件,再执行 `idf.py merge-bin`。 -3. **验证完整固件**:脚本逐字节确认 bootloader、partition-table 和 app 位于 `0x0`、`0x8000` 和 `0x10000`,确认 `flash_args` 使用 8 MB Flash,并输出可从 `0x0` 直刷的 `build/FoloToy-AI-Passport-full.bin`。 +3. **验证完整固件**:脚本逐字节确认 bootloader、partition-table 和 app 位于 `0x0`、`0x8000` 和 `0x10000`,确认 `flash_args` 使用 8 MB Flash,并完整检查小程序 BLE 兼容契约,最后输出 `build/FoloToy-AI-Passport-full.bin`。 4. **上传 artifact**:每次成功构建都上传 `FoloToy-AI-Passport-full.bin`。普通分支只有从该分支手动运行 `workflow_dispatch` 才会构建;普通 push 不触发。 5. **发布 tag**:tag 构建完成后,独立 release job 下载上述 artifact,并创建 GitHub Release。 diff --git a/docs/development/README.md b/docs/development/README.md index fc23503..5be8dff 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -11,6 +11,8 @@ This directory contains AI Passport engineering rules and reusable workflows. Ru - [agent-guide.md](agent-guide.md): AI-assisted development workflow. - [environment-setup.md](environment-setup.md): clean-machine bootstrap for AI agents, including international and mainland China download routes. - [build-and-test.md](build-and-test.md): ESP-IDF build and validation. +- [ble-recovery-compatibility.md](ble-recovery-compatibility.md): mandatory + mini-program BLE install artifact, partition, and bootloader contract. - [coding-conventions.md](coding-conventions.md): source-code and resource conventions. - [CI-validation.md](CI-validation.md): pull-request and main-branch checks. - [CI-build-and-release.md](CI-build-and-release.md): tagged firmware builds and releases. diff --git a/docs/development/README.zh_CN.md b/docs/development/README.zh_CN.md index 81d3531..90c1fe0 100644 --- a/docs/development/README.zh_CN.md +++ b/docs/development/README.zh_CN.md @@ -20,6 +20,8 @@ - [agent-guide.md](agent-guide.md):AI 开发工作流(面向 AI 编程助手:上下文建立、需求拆解、BSP 边界、验收交付格式)。 - [environment-setup.zh_CN.md](environment-setup.zh_CN.md):AI 在全新机器上的环境引导,包含国际与中国大陆下载线路。 - [build-and-test.md](build-and-test.md):构建与验证(ESP-IDF 命令、逻辑测试、改动验证要求)。 +- [ble-recovery-compatibility.zh_CN.md](ble-recovery-compatibility.zh_CN.md):小程序 BLE + 安装所需的产物、分区与 bootloader 强制契约。 - [coding-conventions.md](coding-conventions.md):代码约定(语言风格、复用、注释、测试同步、资源约束等)。 - [CI-build-and-release.md](CI-build-and-release.md):自动构建与发布说明(tag 触发自动编译固件并发布 Release)。 - [CI-validation.md](CI-validation.md):Pull Request 与 main 的自动仓库检查、host tests 和固件验证。 diff --git a/docs/development/ble-recovery-compatibility.md b/docs/development/ble-recovery-compatibility.md new file mode 100644 index 0000000..911b9ff --- /dev/null +++ b/docs/development/ble-recovery-compatibility.md @@ -0,0 +1,70 @@ +

+ 简体中文 · English +

+ +# Mini-Program BLE Firmware Compatibility + +This repository is a derivative-firmware template. Every application built from +it must remain installable by the AI Passport mini-program through the permanent +Recovery already provisioned by the official factory firmware. + +## How installation works + +The application does not implement the BLE flashing service. The user holds UP +while powering on for five seconds; the custom bootloader then starts the +factory-installed Recovery at `0x700000`. Recovery exposes the FFF0–FFF4 BLE +service, verifies the device, receives the application and resource sections, +protects device identity, commits a compatible partition table, and starts the +new application. + +The community artifact is therefore an input to Recovery, not a replacement for +Recovery. A device whose permanent Recovery was erased must first be restored +with the official USB recovery flow. + +## Mandatory contract + +Derivative projects must preserve all of the following: + +- ESP32-C3, 8 MB Flash, ESP-IDF 5.5.3. +- A merged ESP image starting at `0x0`, produced as + `build/FoloToy-AI-Passport-full.bin`. +- One main application image at `0x10000`, no larger than `0x300000` bytes. +- `cardid`: data/NVS at `0x356000`, size `0x4000`. +- `recovery`: app/test at `0x700000`, size `0x100000`. +- The bootloader hook under `bootloader_components/recovery_boot_hook/`, which + enters Recovery after the UP key is held for five seconds. +- A valid partition-table MD5 marker and no partition overlap with either + protected region. +- No device-specific `cardid` payload and no replacement Recovery payload in a + community artifact. + +Applications may add resource partitions, but the partitions must not overlap +the protected regions. Required resource partitions must be included in the +merged artifact rather than declared empty. + +## Enforced validation + +Run: + +```bash +./tools/validate.sh --firmware +``` + +The check builds in an isolated directory, creates the merged image, verifies +the bootloader/table/application offsets, parses the partition table, checks its +MD5 and protected ranges, enforces the 3 MB application limit, rejects protected +payload bytes, and confirms the Recovery boot hook is linked. CI runs the same +gate. Do not publish an artifact when this command fails. + +Upload only `build/FoloToy-AI-Passport-full.bin`; the similarly named app-only +`build/FoloToy-AI-Passport.bin` cannot pass mini-program compatibility checks. + +## Flashing safety during development + +Never run `idf.py erase-flash` on a provisioned device. It destroys both the +per-device identity and permanent Recovery. Prefer mini-program installation or +the segmented `idf.py flash` development command, which does not write an image +for the protected partitions. A raw single-file write from `0x0` is safe only +when its byte range ends before `cardid`; a merged artifact containing later +resource partitions spans the gap and must not be raw-flashed to a provisioned +device. diff --git a/docs/development/ble-recovery-compatibility.zh_CN.md b/docs/development/ble-recovery-compatibility.zh_CN.md new file mode 100644 index 0000000..f6bfcae --- /dev/null +++ b/docs/development/ble-recovery-compatibility.zh_CN.md @@ -0,0 +1,59 @@ +

+ 简体中文 · English +

+ +# 小程序 BLE 固件兼容规范 + +本仓库是二创固件模板。任何基于它开发的应用,都必须保持可由 AI Passport +小程序通过官方默认固件预装的永久 Recovery 安装。 + +## 安装原理 + +玩法应用本身不实现 BLE 刷机服务。用户关机后按住上键开机 5 秒,自定义 +bootloader 跳转到 `0x700000` 的工厂预装 Recovery。Recovery 提供 FFF0–FFF4 +BLE 服务,验证设备后接收应用与资源分区,保护设备身份,写入兼容分区表, +最后启动新应用。 + +因此,社区固件是 Recovery 的安装输入,不是 Recovery 的替代品。如果设备的永久 +Recovery 已被擦除,必须先走官网 USB 恢复流程。 + +## 必须保持的契约 + +二创项目必须同时保留: + +- ESP32-C3、8 MB Flash、ESP-IDF 5.5.3。 +- 从 `0x0` 开始的合并 ESP 镜像,固定产物为 + `build/FoloToy-AI-Passport-full.bin`。 +- 位于 `0x10000` 的主应用镜像,不得超过 `0x300000` 字节。 +- `cardid`:data/NVS,地址 `0x356000`,大小 `0x4000`。 +- `recovery`:app/test,地址 `0x700000`,大小 `0x100000`。 +- `bootloader_components/recovery_boot_hook/` 下的 bootloader hook,上键持续 + 5 秒后进入 Recovery。 +- 有效的分区表 MD5,且所有分区不得与两个保护区重叠。 +- 社区产物不得包含任何单台设备的 `cardid` 数据,也不得携带替换 Recovery + 的数据。 + +应用可以新增资源分区,但不得覆盖保护区。必需资源分区必须打入合并产物, +不得只在分区表声明一个空分区。 + +## 强制验证 + +执行: + +```bash +./tools/validate.sh --firmware +``` + +脚本会在隔离目录构建,生成合并镜像,验证 bootloader、分区表与应用的偏移, +解析分区表并检查 MD5、保护范围和 3 MB 应用上限,拒绝保护分区数据,同时 +确认 Recovery boot hook 已链接。CI 执行同一门禁。该命令失败时不得发布。 + +只上传 `build/FoloToy-AI-Passport-full.bin`。名称相近的应用单镜像 +`build/FoloToy-AI-Passport.bin` 无法通过小程序兼容检测。 + +## 开发烧录安全 + +已写入设备身份的机器严禁执行 `idf.py erase-flash`,否则会同时破坏单机身份与永久 +Recovery。优先使用小程序安装,或使用不会写保护分区镜像的分段 `idf.py flash`。 +只有单文件的字节范围在 `cardid` 之前结束时,从 `0x0` 直接写入才是安全的; +若合并产物包含位于 `cardid` 之后的资源分区,就不得对已写身份的设备做单文件直刷。 diff --git a/docs/development/build-and-test.md b/docs/development/build-and-test.md index 0428cfc..9ffbe2a 100644 --- a/docs/development/build-and-test.md +++ b/docs/development/build-and-test.md @@ -8,7 +8,10 @@ Use ESP-IDF 5.5.3. On a clean machine or when the toolchain is missing, follow the [environment bootstrap](environment-setup.md) first. > Prefer `./tools/validate.sh --firmware` for firmware builds and flash its -> verified `build/FoloToy-AI-Passport-full.bin` at offset `0x0`. Treat +> verified `build/FoloToy-AI-Passport-full.bin` at offset `0x0` only when the +> target is blank or the merged byte range ends before protected `cardid`. +> On a provisioned device, prefer mini-program install or segmented +> `idf.py flash`. Treat > `idf.py build` and `idf.py flash` as incremental development commands, not the > default delivery path. @@ -29,7 +32,7 @@ regenerated. The tracked `dependencies.lock` pins Managed Component resolution. After changing an `idf_component.yml`, regenerate the lock with ESP-IDF 5.5.3, review version changes, and commit it with the manifest. An ordinary build must not leave an unexplained lock-file diff. -Firmware validation uses a fresh temporary build directory and an isolated `sdkconfig` generated from the tracked defaults. It does not consume or overwrite a developer's root `sdkconfig`, and it copies only the verified merged image to `build/FoloToy-AI-Passport-full.bin`. +Firmware validation uses a fresh temporary build directory and an isolated `sdkconfig` generated from the tracked defaults. It does not consume or overwrite a developer's root `sdkconfig`, and it copies only the verified merged image to `build/FoloToy-AI-Passport-full.bin`. The gate also enforces the [mini-program BLE compatibility contract](ble-recovery-compatibility.md): protected partition addresses, application size, partition-table MD5, absence of protected payload data, and the Recovery bootloader hook. The baseline also has a hardware-independent logic test: @@ -44,10 +47,14 @@ Use the unified validation entry point: ```bash ./tools/validate.sh --static # repository checks, workflows, links, secrets, host tests -./tools/validate.sh --firmware # build, merge-bin, image offsets and byte verification +./tools/validate.sh --firmware # build, merge-bin, offsets, and BLE compatibility ./tools/validate.sh # complete gate; requires an activated ESP-IDF environment ``` CI calls the same script. Fix the shared script or environment if local and CI behavior differs; do not duplicate command sequences in workflows. Hardware-affecting changes must also run the applicable on-device checklist in the hardware guide. Report compilation separately from physical-device validation. + +Never upload the app-only `build/FoloToy-AI-Passport.bin` to the community. Only +the validated `build/FoloToy-AI-Passport-full.bin` contains the structure the +mini-program can inspect and transform safely. diff --git a/docs/development/build-and-test.zh_CN.md b/docs/development/build-and-test.zh_CN.md index 73c81cd..ad1eec1 100644 --- a/docs/development/build-and-test.zh_CN.md +++ b/docs/development/build-and-test.zh_CN.md @@ -8,7 +8,9 @@ [环境引导](environment-setup.zh_CN.md)完成安装。 > 固件编译优先运行 `./tools/validate.sh --firmware`,烧录优先把验证通过的 -> `build/FoloToy-AI-Passport-full.bin` 写入 `0x0`。`idf.py build` 和 +> `build/FoloToy-AI-Passport-full.bin` 写入空白设备;对已有身份的设备,只有合并文件 +> 在保护区 `cardid` 之前结束时才可从 `0x0` 直刷,其余情况优先用小程序或分段 +> `idf.py flash`。`idf.py build` 和 > `idf.py flash` 只作为增量开发命令,不作为默认交付方式。 ```bash @@ -27,7 +29,7 @@ target 或已跟踪 defaults 时,先保留有意的本地设置,再运行 仓库提交 `dependencies.lock` 以固定 ESP-IDF Managed Components 的解析结果。修改 `idf_component.yml` 后必须使用 ESP-IDF 5.5.3 重新生成锁文件、review 版本变化并与 manifest 一起提交;普通构建不应产生未提交的锁文件差异。 -固件门禁使用全新的临时构建目录,并从仓库 `sdkconfig.defaults` 生成隔离的 `sdkconfig`。它不会读取或覆盖开发者根目录的 `sdkconfig`,只把验证通过的合并镜像复制到 `build/FoloToy-AI-Passport-full.bin`。 +固件门禁使用全新的临时构建目录,并从仓库 `sdkconfig.defaults` 生成隔离的 `sdkconfig`。它不会读取或覆盖开发者根目录的 `sdkconfig`,只把验证通过的合并镜像复制到 `build/FoloToy-AI-Passport-full.bin`。门禁同时强制检查[小程序 BLE 兼容契约](ble-recovery-compatibility.zh_CN.md):保护分区地址、应用大小、分区表 MD5、保护区数据不入包,以及 Recovery bootloader hook。 当前基线含一个可独立运行的纯逻辑测试: @@ -42,10 +44,13 @@ cc -std=c11 -Wall -Wextra -Werror -Imain \ ```bash ./tools/validate.sh --static # 仓库一致性、workflow、文档链接、敏感信息、host tests -./tools/validate.sh --firmware # ESP-IDF build、merge-bin、固件偏移校验 +./tools/validate.sh --firmware # ESP-IDF build、merge-bin、偏移与 BLE 兼容校验 ./tools/validate.sh # 完整验证 ``` 完整验证要求预先激活 ESP-IDF 5.5.3。CI 与本地使用同一脚本;若 CI 和本地行为不同,应先修复脚本或环境,而不是维护两份命令。 涉及物理外设的改动必须在真机运行硬件指南验收清单,并把“编译通过”与“硬件验证通过”分开记录。 + +社区只能上传验证通过的 `build/FoloToy-AI-Passport-full.bin`,不得上传应用单镜像 +`build/FoloToy-AI-Passport.bin`,后者没有小程序可安全解析与转换的完整结构。 diff --git a/docs/development/publish-to-community.md b/docs/development/publish-to-community.md index 415ed0d..042dc5e 100644 --- a/docs/development/publish-to-community.md +++ b/docs/development/publish-to-community.md @@ -26,7 +26,11 @@ The skill's `SKILL.md` defines the exact workflow: inspect the project, prepare ## What the assistant will need from you -- **Firmware**: a single merged ESP `.bin` (flashed from `0x0`). Build it with `./tools/validate.sh --firmware` or `idf.py build` when needed. +- **Firmware**: the single merged ESP image + `build/FoloToy-AI-Passport-full.bin`. It must pass + `./tools/validate.sh --firmware`, including the + [mini-program BLE compatibility contract](ble-recovery-compatibility.md). + Never substitute the app-only `.bin` produced by `idf.py build`. - **Cover**: a representative JPEG / PNG / WebP image (<= 10 MiB). - **Source**: the public HTTPS Git page for the firmware repository — GitHub, Gitee, GitLab, Codeberg, or another publicly reachable HTTPS Git repository page. A fork owner publishes from their fork's source page, resolved from `git remote -v`. @@ -36,6 +40,8 @@ The skill's `SKILL.md` defines the exact workflow: inspect the project, prepare - Validation, drafting, and preview that is not confirmed by the author does **not** authorize upload. - Authorization credentials are never requested, received, or stored by the assistant. The creator registers or signs in on the official site and approves the displayed code; the assistant never handles their password. - Never retry a rejected upload automatically. Report the server response and resolve the cause with the creator first. +- Do not weaken, bypass, or remove the BLE compatibility gate merely to make a + community submission pass. Fix the image layout or build packaging instead. ## How the assistant installs the skill @@ -53,4 +59,3 @@ Only commit the summary and cover; do not store the firmware `.bin` here. Use th `FoloToy/ai-passport`. This keeps the release's application discoverable in-repository for later querying. - diff --git a/docs/development/publish-to-community.zh_CN.md b/docs/development/publish-to-community.zh_CN.md index f23a613..bedef36 100644 --- a/docs/development/publish-to-community.zh_CN.md +++ b/docs/development/publish-to-community.zh_CN.md @@ -31,7 +31,9 @@ skill 的 `SKILL.md` 定义了精确流程:检查项目、准备中英文标 ## 你需要提供给助手的东西 -- **固件**:单个合并的 ESP `.bin`(从 `0x0` 烧录)。必要时用 `./tools/validate.sh --firmware` 或 `idf.py build` 构建。 +- **固件**:固定使用单个合并镜像 `build/FoloToy-AI-Passport-full.bin`, + 且必须通过 `./tools/validate.sh --firmware` 与[小程序 BLE 兼容契约](ble-recovery-compatibility.zh_CN.md)。 + 不得用 `idf.py build` 生成的应用单镜像替代。 - **封面**:一张代表产品的 JPEG / PNG / WebP 图(≤ 10 MiB)。 - **源码**:固件仓库的公开 HTTPS Git 项目页——GitHub、Gitee、GitLab、Codeberg 或其它公开可达的 HTTPS Git 仓库页。fork 所有者从其 fork 的来源页发布,从 `git remote -v` 解析。 @@ -41,6 +43,7 @@ skill 的 `SKILL.md` 定义了精确流程:检查项目、准备中英文标 - 未经作者确认的验证、起草与预览**不授权上传**。 - 助手绝不索取、接收或存储授权凭证。由创作者在官方站点注册或登录并批准显示的代码;助手不接触其密码。 - 不自动重试被拒的上传。先把服务端响应展示给创作者,查清原因再处理。 +- 不得为了让社区提交通过而弱化、绕过或删除 BLE 兼容门禁;应修复镜像布局或打包流程。 ## 助手如何安装该 skill diff --git a/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md b/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md index 38d188f..490054b 100644 --- a/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md +++ b/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md @@ -167,7 +167,11 @@ Accurate production SOC requires the cell parameters, CW2017 datasheet/vendor pr ## 10. Flash, console, and memory -The current product and firmware baseline uses 8 MB Flash. `sdkconfig.defaults` fixes the image to 8 MB and disables automatic flash-size header rewriting. `partitions.csv` defines 24 KB NVS, 4 KB PHY data, and one 3 MB factory application without OTA slots. A detected non-8-MB device does not match this baseline; identify the board and flash part before changing the project default. +The current product and firmware baseline uses 8 MB Flash. `sdkconfig.defaults` fixes the image to 8 MB and disables automatic flash-size header rewriting. `partitions.csv` defines 24 KB NVS, 4 KB PHY data, one 3 MB factory application, protected `cardid` at `0x356000`, and permanent Recovery at `0x700000`. This is not an ESP-IDF dual-slot OTA layout: the factory-installed Recovery performs BLE installation and must remain at its fixed address. The bootloader enters it when UP/GPIO0 is held for five seconds. A detected non-8-MB device does not match this baseline; identify the board and flash part before changing the project default. + +Do not erase a provisioned device or move/overlap the protected partitions. +Community firmware contains neither device identity nor a replacement Recovery +payload. See the [BLE compatibility contract](../development/ble-recovery-compatibility.md). The console is USB Serial/JTAG. Do not switch to the UART0 default output without resolving its GPIO21 conflict with the backlight. diff --git a/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md b/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md index fbe182a..03f5af1 100644 --- a/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md +++ b/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md @@ -226,7 +226,10 @@ SOC 准确度取决于电芯与 profile 的匹配程度。本驱动给出的是 ## 10. Flash、控制台和资源预算 -当前产品与固件基线使用 8 MB Flash。`sdkconfig.defaults` 固定使用 8 MB Flash 镜像配置,并关闭 `CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE`(不按探测容量回写镜像头,便于 `idf.py merge-bin`);`partitions.csv` 提供 24 KB NVS、4 KB PHY data 和 3 MB factory app 分区,无 OTA 槽。若实机探测结果不是 8 MB,则该设备不符合当前基线;修改项目默认值前应先确认板卡和 Flash 料号。 +当前产品与固件基线使用 8 MB Flash。`sdkconfig.defaults` 固定使用 8 MB Flash 镜像配置,并关闭 `CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE`(不按探测容量回写镜像头,便于 `idf.py merge-bin`);`partitions.csv` 提供 24 KB NVS、4 KB PHY data、3 MB factory app、位于 `0x356000` 的保护 `cardid`,以及位于 `0x700000` 的永久 Recovery。这不是 ESP-IDF 双槽 OTA 布局;工厂预装 Recovery 负责 BLE 安装,且必须保持固定地址。开机持续按住上键/GPIO0 5 秒时,bootloader 会进入 Recovery。若实机探测结果不是 8 MB,则该设备不符合当前基线;修改项目默认值前应先确认板卡和 Flash 料号。 + +不得擦除已写身份的设备,也不得移动或覆盖保护分区。社区固件既不包含单机身份, +也不携带替换 Recovery 的数据。详见 [BLE 兼容契约](../development/ble-recovery-compatibility.zh_CN.md)。 控制台固定为 USB Serial/JTAG,不使用 UART0 默认输出,因为其 TX GPIO21 与背光冲突。任何日志接口修改都必须同时检查引脚占用。 diff --git a/partitions.csv b/partitions.csv index 67aeb04..d35f674 100644 --- a/partitions.csv +++ b/partitions.csv @@ -2,3 +2,5 @@ nvs, data, nvs, 0x9000, 0x6000, phy_init, data, phy, 0xf000, 0x1000, factory, app, factory, 0x10000, 0x300000, +cardid, data, nvs, 0x356000, 0x4000, +recovery, app, test, 0x700000, 0x100000, diff --git a/sdkconfig.defaults b/sdkconfig.defaults index d593882..b74e1d6 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -7,11 +7,21 @@ CONFIG_IDF_TARGET="esp32c3" CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y # 固定 8MB 镜像头,关闭 detect,便于 idf.py merge-bin。 CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE=n -# 无 OTA 的硬件演示固件;3MB app 分区给 Wi-Fi/NimBLE 留出升级余量。 +# 3 MB 应用上限与小程序 BLE Recovery 安装器保持一致。分区表 +# 还固定保留 cardid@0x356000 与 recovery@0x700000,二创不得改动。 CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" +# 开机持续按住上键(GPIO0)5 秒,由自定义 bootloader 跳转到工厂 +# 预装的 0x700000 Recovery。这些选项为 bootloader 提供长按检测配置。 +CONFIG_BOOTLOADER_FACTORY_RESET=y +CONFIG_BOOTLOADER_NUM_PIN_FACTORY_RESET=0 +CONFIG_BOOTLOADER_FACTORY_RESET_PIN_LOW=y +CONFIG_BOOTLOADER_OTA_DATA_ERASE=y +CONFIG_BOOTLOADER_DATA_FACTORY_RESET="" +CONFIG_BOOTLOADER_HOLD_TIME_GPIO=5 + # --- 控制台:USB-Serial-JTAG(C3 原生 USB,GPIO18/19)--- # 不用 UART0:其默认 TX=GPIO21 与本板背光引脚冲突。 CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y diff --git a/tests/test_verify_firmware.py b/tests/test_verify_firmware.py new file mode 100644 index 0000000..077003d --- /dev/null +++ b/tests/test_verify_firmware.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Host tests for the mini-program firmware compatibility parser.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import struct +import sys +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location( + "verify_firmware", ROOT / "tools" / "verify_firmware.py" +) +assert SPEC and SPEC.loader +VERIFY = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = VERIFY +SPEC.loader.exec_module(VERIFY) + + +def sample_table() -> bytes: + entries = ( + (1, 2, 0x9000, 0x6000, "nvs"), + (1, 1, 0xF000, 0x1000, "phy_init"), + (0, 0, 0x10000, 0x300000, "factory"), + (1, 2, 0x356000, 0x4000, "cardid"), + (0, 0x20, 0x700000, 0x100000, "recovery"), + ) + raw = bytearray(b"\xff" * VERIFY.PARTITION_TABLE_SIZE) + for index, (kind, subtype, offset, size, label) in enumerate(entries): + VERIFY.ENTRY.pack_into( + raw, + index * VERIFY.ENTRY.size, + 0x50AA, + kind, + subtype, + offset, + size, + label.encode().ljust(16, b"\0"), + 0, + ) + marker = len(entries) * VERIFY.ENTRY.size + struct.pack_into(" None: + partitions, found_md5 = VERIFY.parse_partition_table(sample_table()) + self.assertTrue(found_md5) + self.assertEqual(partitions[-2].label, "cardid") + self.assertEqual(partitions[-1].offset, VERIFY.RECOVERY_OFFSET) + + def test_rejects_bad_md5(self) -> None: + raw = bytearray(sample_table()) + raw[28] ^= 1 + with self.assertRaisesRegex(ValueError, "MD5"): + VERIFY.parse_partition_table(bytes(raw)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/validate.sh b/tools/validate.sh index 8f2e44a..07217f4 100755 --- a/tools/validate.sh +++ b/tools/validate.sh @@ -28,6 +28,7 @@ run_static_checks() { tests/test_ui_pixel_math.c main/ui_pixel_math.c \ -o "${test_dir}/test_ui_pixel_math" "${test_dir}/test_ui_pixel_math" + python3 tests/test_verify_firmware.py rm -rf "${test_dir}" echo "Host tests: PASS" } @@ -49,7 +50,8 @@ run_firmware_checks() ( idf.py -B "${validation_build_dir}" merge-bin \ -o "${validation_build_dir}/FoloToy-AI-Passport-full.bin" python3 tools/verify_firmware.py "${validation_build_dir}" - install -D -m 0644 \ + mkdir -p "${repo_root}/build" + install -m 0644 \ "${validation_build_dir}/FoloToy-AI-Passport-full.bin" \ "${repo_root}/build/FoloToy-AI-Passport-full.bin" echo "Firmware build: PASS" diff --git a/tools/verify_firmware.py b/tools/verify_firmware.py index 13388e0..082b741 100755 --- a/tools/verify_firmware.py +++ b/tools/verify_firmware.py @@ -3,7 +3,10 @@ from __future__ import annotations +import hashlib +import struct import sys +from dataclasses import dataclass from pathlib import Path @@ -13,6 +16,116 @@ EXPECTED_IMAGES = ( (0x10000, "FoloToy-AI-Passport.bin"), ) +FLASH_SIZE = 8 * 1024 * 1024 +PARTITION_TABLE_OFFSET = 0x8000 +PARTITION_TABLE_SIZE = 0xC00 +APP_MAX_SIZE = 0x300000 +CARDID_OFFSET = 0x356000 +CARDID_SIZE = 0x4000 +RECOVERY_OFFSET = 0x700000 +RECOVERY_SIZE = 0x100000 +ENTRY = struct.Struct(" int: + return self.offset + self.size + + +def parse_partition_table(raw: bytes) -> tuple[list[Partition], bool]: + """Parse an ESP-IDF table and verify its optional MD5 marker.""" + if len(raw) < PARTITION_TABLE_SIZE: + raise ValueError("partition table is truncated") + + partitions: list[Partition] = [] + found_md5 = False + for cursor in range(0, PARTITION_TABLE_SIZE, ENTRY.size): + magic = int.from_bytes(raw[cursor : cursor + 2], "little") + if magic == 0xFFFF: + break + if magic == 0xEBEB: + expected = hashlib.md5(raw[:cursor]).digest() + actual = raw[cursor + 16 : cursor + 32] + if actual != expected: + raise ValueError("partition table MD5 marker does not match") + found_md5 = True + break + if magic != 0x50AA: + raise ValueError(f"invalid partition entry at table offset 0x{cursor:x}") + + _, kind, subtype, offset, size, label_raw, _ = ENTRY.unpack_from(raw, cursor) + label = label_raw.split(b"\0", 1)[0].decode("ascii", "strict") + if not label or not size or offset < 0x9000 or offset + size > FLASH_SIZE: + raise ValueError(f"invalid partition bounds for {label!r}") + partitions.append(Partition(kind, subtype, offset, size, label)) + + if not partitions: + raise ValueError("partition table is empty") + return partitions, found_md5 + + +def verify_recovery_contract(merged: bytes, build_dir: Path) -> None: + """Enforce the artifact/layout contract used by mini-program BLE install.""" + table = merged[ + PARTITION_TABLE_OFFSET : PARTITION_TABLE_OFFSET + PARTITION_TABLE_SIZE + ] + partitions, found_md5 = parse_partition_table(table) + if not found_md5: + raise ValueError("partition table has no MD5 marker") + + by_label = {item.label: item for item in partitions} + expected = { + "factory": Partition(0, 0, 0x10000, APP_MAX_SIZE, "factory"), + "cardid": Partition(1, 2, CARDID_OFFSET, CARDID_SIZE, "cardid"), + "recovery": Partition(0, 0x20, RECOVERY_OFFSET, RECOVERY_SIZE, "recovery"), + } + for label, wanted in expected.items(): + if by_label.get(label) != wanted: + raise ValueError(f"partition {label!r} must remain {wanted}, got {by_label.get(label)}") + + ordered = sorted(partitions, key=lambda item: item.offset) + for left, right in zip(ordered, ordered[1:]): + if left.end > right.offset: + raise ValueError(f"partitions {left.label!r} and {right.label!r} overlap") + for item in partitions: + if item.label != "cardid" and item.offset < CARDID_OFFSET + CARDID_SIZE and CARDID_OFFSET < item.end: + raise ValueError(f"partition {item.label!r} overlaps protected cardid") + if item.label != "recovery" and item.offset < RECOVERY_OFFSET + RECOVERY_SIZE and RECOVERY_OFFSET < item.end: + raise ValueError(f"partition {item.label!r} overlaps permanent Recovery") + + app_path = build_dir / "FoloToy-AI-Passport.bin" + app_size = app_path.stat().st_size + if app_size > APP_MAX_SIZE: + raise ValueError(f"application is {app_size} bytes; BLE limit is {APP_MAX_SIZE}") + if len(merged) <= 0x10000 or merged[0x10000] != 0xE9: + raise ValueError("merged artifact has no ESP application image at 0x10000") + + # A derivative may add resource partitions after cardid. The merged file is + # still acceptable only if protected regions contain padding, never a real + # device identity or a replacement Recovery payload. + for label, offset, size in ( + ("cardid", CARDID_OFFSET, CARDID_SIZE), + ("recovery", RECOVERY_OFFSET, RECOVERY_SIZE), + ): + payload = merged[offset : min(len(merged), offset + size)] + if any(byte != 0xFF for byte in payload): + raise ValueError(f"merged artifact contains forbidden {label} payload bytes") + + bootloader = (build_dir / "bootloader" / "bootloader.bin").read_bytes() + if RECOVERY_BOOT_MARKER not in bootloader: + raise ValueError("bootloader is missing the 5-second UP Recovery hook") + + print(f"Mini-program BLE contract: PASS (app {app_size} / {APP_MAX_SIZE} bytes)") + def main() -> int: build_dir = Path(sys.argv[1] if len(sys.argv) > 1 else "build").resolve() @@ -40,10 +153,16 @@ def main() -> int: return 1 print(f"Verified {relative_name}: {len(image)} bytes at 0x{offset:x}") - if len(merged) > 8 * 1024 * 1024: + if len(merged) > FLASH_SIZE: print("ERROR: merged firmware exceeds 8 MB", file=sys.stderr) return 1 + try: + verify_recovery_contract(merged, build_dir) + except (OSError, UnicodeDecodeError, ValueError) as error: + print(f"ERROR: {error}", file=sys.stderr) + return 1 + print(f"Merged firmware: PASS ({len(merged)} bytes, flash at 0x0)") return 0