# Securex NVR 插件开发指南 — Fix84R5 历史补全与 Fix107 当前基线

> **Evidence:** [H] supplied Fix73 guides; [T] project target; [V] requires source/runtime verification.

## 适用范围与证据级别

This guide restores the development reference using the supplied Fix73 documents. **[H]** means directly supported by those documents; **[T]** means the target baseline supplied in project context; **[V]** means must be verified against the actual Fix84R5/ Fix107 source and runtime. It is not an original recovered Fix84R5 release artifact. Do not use inferred fields as a guarantee of current implementation.

## 当前目标环境（2026-10-18）

| Component | Target / historical status |
|---|---|
| Frigate | **v0.18.2 [T]**; historical Fix73 document: v0.18.0 [H] |
| Universal | **v1.9.119 Fix104R4 [T]**; historical Fix73: v1.9.92 [H] |
| System Update Center | **v1.0.51 [T]**; historical Fix73: v1.0.34 [H] |
| Host Updater | historical Fix73: v1.0.17 [H]; current version **[V]** |
| Kiosk | historical Fix73: v0.3.9 [H]; current version **[V]** |
| Installer | Fix107 / Frigate 0.18.2 [T] |
| 2026-10-04 Fix84R5 | exact code/API changes **[V]** |

The Frigate and Universal numbers describe different layers; updating a public manifest does not upgrade an installed host.

## 已确认的历史 API 与插件约定

[H] Prefer Universal Plugin API over repeated patches to Frigate core; keep each feature as an independently installable plugin. Default to `config_apply: hot` when supported. First install or code changes may require a reload. Never include model weights, recordings, user secrets, training data or database backups in ordinary ZIP files. Maintain stable plugin IDs and navigation keys. Changes to the Universal baseline must be reflected in Store, installer, offline cache, ISO and documentation.

## 插件工程与打包

[H] Reference layout:

```text
tynvr_module_example/
├── manifest.json
├── plugin.py
├── config.example.yml
├── README.md
├── host-manifest.json       # only if host features are needed
└── ui/
    └── index.html
```

**The ZIP root contains these files directly**, not an extra wrapping folder. Delete `__pycache__`, `.pyc`, temporary logs and test credentials. The code path is `/home/frigate/config/plugins/<plugin_id>/` in the historical deployment. Check actual Fix107 mount/config paths before production use [V].

## 插件清单示例

[H] Example adapted from Fix73, not a newly verified Fix107 schema:

```json
{
  "id": "tynvr_module_example",
  "name": "Example Plugin",
  "version": "1.0.0",
  "description": "Example plugin",
  "enabled": true,
  "kind": "plugin",
  "config_apply": "hot",
  "first_install_restart": true,
  "navigation_user_toggle": true,
  "navigation_default_visible": true,
  "navigation": [{
    "mount": "main.sidebar",
    "key": "securex_example",
    "url": "/api/securex-example/",
    "view": "iframe",
    "order": 50,
    "visibility": "loaded",
    "icon": "bot"
  }]
}
```

The minimum mandatory fields in Fix73 were stable `id`, `name`, `version`, `description`, `enabled`. Verify newer required keys, permissions and validation rules against the running Plugin Manager [V].

## 后端插件 API

[H] Historical base class and router example:

```python
from pathlib import Path
from typing import Any
from fastapi import APIRouter
from frigate.plugins.base import FrigatePlugin

class Plugin(FrigatePlugin):
    def __init__(self, frigate_config: Any, plugin_dir: Path, stop_event=None):
        super().__init__(frigate_config, plugin_dir, stop_event)
        self._router = APIRouter(tags=["example"])

    @property
    def router(self):
        return self._router
```

[H] Historical Plugin Manager interfaces included `get_public_config()`, `update_config()`, and `run_action()`. **Exact signatures, permission checks, CSRF requirements and supported return shapes must be inspected in Fix107 source [V].** Do not copy a signature from this guide into production without checking the live base class. Secrets returned to browsers must be masked.

## 导航、语言、主题与移动端

[H] Supported historical navigation mounts: `main.sidebar` and `settings.sidebar.plugins`; use stable iframe routes such as `/api/securex-example/`. Fix72 introduced native-looking settings and `navigation_user_toggle: true`; hiding a menu item does **not** disable the plugin. `actions[].label` should use a string translation key; Fix73 tolerated localized objects to avoid UI crashes.

[H] At minimum cover `zh-CN`, `zh-Hant` / `zh-TW`, `en`; use theme-aware UI and avoid duplicating Frigate's existing header/navigation inside iframe. [T] Store and docs also use Spanish and other languages; translate every user-visible label, action, error, empty state, confirmation and date/number format. Test mobile sidebar and touch targets. **Current localization keys and UI bridge APIs remain [V].**

## 权限、认证与安全

[H] Plugin navigation and **direct routes/APIs** must enforce administrator-only access by default; hiding UI is not RBAC. Use authenticated requests, validate state-changing operations, apply CSRF protections as required by the host, and do not leak tokens or secrets in logs. SSH Manager's historical controlled operations were `status`, `enable`, `disable`, `set_port`; arbitrary root shell was forbidden. Validate port conflicts and `sshd -t`, with rollback on failure.

[T] Port 8971 is the default authenticated management entry in the current installation flow; host port 5000 is optional and defaults off. **Do not assume an optional Access Control plugin is preinstalled.** [V] Before limiting a 5000 API whitelist to GET, inspect the core frontend's real request methods and dependencies. Never deploy a blanket method restriction based only on this guide.

## 宿主服务与 Sidecar

[H] Generic Plugin Host Supervisor, introduced in Fix69, lets new host-capable plugins declare Docker sidecars using `host-manifest.json` without patching Universal for each plugin. Historical service files:

```text
/usr/local/lib/securex-plugin-host/securex_plugin_host.py
/etc/systemd/system/securex-plugin-host.service
/etc/systemd/system/securex-plugin-host.path
/etc/systemd/system/securex-plugin-host.timer
/var/lib/securex-plugin-host/state.json
```

[H] Historical declarative example:

```json
{
  "schema_version": 1,
  "plugin_id": "tynvr_module_example",
  "config_file": "config.yml",
  "enabled_config_path": "enabled",
  "status_file": "host_status.json",
  "service": {
    "name": "securex-example",
    "image": "vendor/example:latest",
    "restart": "unless-stopped",
    "network": "frigate",
    "gpu": "auto_nvidia",
    "data_dirs": [{"path": "/home/frigate/config/example", "mode": "755"}],
    "volumes": [{"source": "/home/frigate/config/example", "target": "/data", "mode": "rw"}],
    "ports": [{"host_ip": "127.0.0.1", "host_port": 19000, "container_port": 9000, "protocol": "tcp"}]
  },
  "cleanup_on_remove": []
}
```

[H] Placeholders: `${plugin_dir}`, `${config_dir}`, `${host.lan_ip}`, `${frigate.network}`, `${config.foo.bar}`, `${env.NAME}`. `network: frigate` discovers Frigate Docker network; `network: host` only when necessary. `render_files` can generate controlled host configs. No arbitrary root shell hooks. Persistent models, recordings and history must not appear in `cleanup_on_remove`. Historical Store minimum `min_tynvr_version >= 1.9.88` for Host Manifest; **verify current minimum [V]**.

[H] Workflow: install/update -> reconcile -> start; configuration change -> spec hash comparison -> recreate only when changed; disable/uninstall -> remove owned sidecar, cleanup only declared temporary paths. [T] AI Pool and Matter may also have compatibility reconcilers; do not assume all existing plugins use Generic Host.

## 插件生命周期与数据安全

[H] Install, upgrade, disable, uninstall are distinct operations. Keep user configuration and persistent directories across upgrade. Confirm disabling a plugin removes host services only when owned by that plugin; never remove shared Docker images/volumes indiscriminately. Validate ownership labels before cleanup. A package rollback should restore previous code without erasing user data.

[V] Test installation on a fresh host, upgrade from a previous version, failed partial install, restart, network unavailable, Docker unavailable, duplicate port, disabled state and uninstall. For NVR systems, prefer operations that avoid interrupting active recordings. Avoid restarting networking or flushing NIC addresses in a plugin installer.

## 更新中心与商城发布

[H] Release consistency checklist: `catalog.json` plugin version, package SHA256, public download URL, homepage/release notes, System Update manifest, Fresh Installer, offline-cache, ISO Build Kit, and developer docs. Do not change a checksum unless the downloadable archive actually changed. Do not advertise an artifact before verifying the URL and hash. Historical Universal's Generic Host installation was integrated in `install_tynvr_universal.py` for consistent ISO/host updater/manual installation.

[T] The target release line is Fix107 / Frigate 0.18.2. **A manifest edit is metadata only; it does not change installed Docker images, Frigate code, or the running service.**

## 测试矩阵与故障排查

Suggested non-destructive validation:

```bash
python3 -m json.tool manifest.json >/dev/null
python3 -m py_compile plugin.py
# If shell files are present:
bash -n install.sh
unzip -l plugin.zip
sha256sum plugin.zip
```

Test roles (administrator/member/unauthenticated), direct URL/API access, light/dark, mobile, three core languages, settings persistence, secrets masking, CSRF, installation/upgrade/uninstall, host sidecar ownership, no-data-loss, and recordings continuing normally. For diagnosing host state (read-only):

```bash
systemctl status securex-plugin-host.service --no-pager
systemctl list-timers --all | grep securex
journalctl -u securex-plugin-host.service -n 100 --no-pager
docker ps -a --format 'table {{.Names}}	{{.Status}}'
```

A missing service may simply indicate a different installation layout; confirm paths first.

## Fix84R5 历史缺口

**Important:** None of the three supplied documents contains the actual **2026-10-04 Fix84R5** source diff, release notes, schema migration, or validated plugin API signatures. Therefore these exact changes cannot be reconstructed as historical fact. To finish the Fix84R5 chapter, obtain one of: original Fix84R5 Universal ZIP/source tree, installer ZIP, Store catalog history, or release/commit diff. Record the actual changed files, API changes, compatibility requirements, migrations, breaking changes and regression tests. This section is intentionally an evidence gap rather than invented history.

## Fix107 迁移核对清单

1. [T] Confirm official Frigate v0.18.2 runtime and image tag; distinguish it from installed Universal version.
2. [T] Confirm Universal v1.9.119 Fix104R4 package, SHA256 and running overlay.
3. [V] Compare `FrigatePlugin` base, Plugin Manager APIs, `manifest.json` schema and auth/CSRF routes against live source.
4. [V] Verify Host Supervisor version, supported schema, ownership labels, reconcilers and plugin install paths.
5. [T] Keep Access Control optional; no default 5000 exposure; test 8971 login and 5000 method behavior separately.
6. [V] Check all installed plugins for stable navigation keys, friendly names, i18n and responsive settings UI.
7. [V] Confirm Store `catalog.json`, public manifests, hashes and installers match released files.
8. [V] Run safe upgrade/rollback and preserve recordings, users, configurations and sidecar data.
9. [V] Collect original Fix84R5 artifacts before claiming historical compatibility.

## 原始资料与核验状态

Supplied references: `Securex_Nvr_Plugin_Developer_Guide_2026-09-27_R63_6_2_Fix73_CN.md`, `_EN.md`, `_TW.md`. The CN version has the most detailed historical manifest/API/host examples; the EN/TW versions are shorter. Target version values reflect the current project release discussion, **not verification of an attached Fix107 source archive**. Keep the original three files unmodified for audit.

---

## 附录：原始 Fix73 文档全文

# Securex NVR 插件开发文档 — R63.6.2 Mixed Fix73

当前正式开发基线：Frigate v0.18.0；Universal v1.9.92 Fix73；System Update Center v1.0.34；Host Updater v1.0.17；Kiosk v0.3.9。

## 1. 开发原则

- 优先通过 Universal Plugin API 扩展 Frigate，不重复 patch Frigate 核心。
- 一个功能一个插件，独立安装、升级、禁用、卸载。
- 普通配置使用 `config_apply: hot`；首次安装/代码升级才允许一次重载。
- 主菜单、Settings 菜单、语言、主题、CSRF、iframe 都由 Universal 公共能力处理。
- 大模型、训练数据、录像、缓存、数据库不要放在插件 ZIP 内。

## 2. 基本目录

```text
tynvr_module_example/
├── manifest.json
├── plugin.py
├── config.example.yml
├── README.md
├── host-manifest.json      # 仅 Host 插件需要
└── ui/
    └── index.html
```

ZIP 顶层必须直接包含插件根文件，不要再套额外目录。发布前删除 `__pycache__`、`.pyc`、临时日志、Token、测试数据。

## 3. manifest.json

至少包含稳定 `id`、`name`、`version`、`description`、`enabled`。推荐：

```json
{
  "id": "tynvr_module_example",
  "name": "Example Plugin",
  "version": "1.0.0",
  "enabled": true,
  "kind": "plugin",
  "config_apply": "hot",
  "first_install_restart": true,
  "navigation_user_toggle": true,
  "navigation_default_visible": true,
  "navigation": [
    {
      "mount": "main.sidebar",
      "key": "securex_example",
      "url": "/api/securex-example/",
      "view": "iframe",
      "order": 50,
      "visibility": "loaded",
      "icon": "bot"
    }
  ]
}
```

主侧栏 `key` 必须稳定且不可与其他插件重复。Fix67+ 支持 Frigate/Lucide `bot`、`cctv` 等图标映射。

## 4. plugin.py

当前 Universal 以 `FrigatePlugin` 为标准插件基类：

```python
from pathlib import Path
from typing import Any
from fastapi import APIRouter
from frigate.plugins.base import FrigatePlugin

class Plugin(FrigatePlugin):
    def __init__(self, frigate_config: Any, plugin_dir: Path, stop_event=None):
        super().__init__(frigate_config, plugin_dir, stop_event)
        self._router = APIRouter(tags=["example"])

    @property
    def router(self):
        return self._router
```

Plugin Manager 配置页应实现 Universal 当前接口，例如 `get_public_config()`、`update_config()`、`run_action()`；Secret 返回浏览器时必须掩码。

## 5. UI / Navigation

- 主菜单：`mount: main.sidebar`
- Settings 插件侧栏：`mount: settings.sidebar.plugins`
- iframe URL 必须稳定，推荐 `/api/securex-<feature>/`。
- UI 必须跟随 Frigate 深浅主题与当前语言。
- 完整支持 `zh-CN`、`zh-Hant`/`zh-TW`、`en`。
- 不要在 iframe 内重复显示 Frigate 已经提供的页面标题、侧栏或全局导航。

## 6. Fix69 Generic Plugin Host Supervisor v1

Fix69 起，**新插件如果需要宿主 Docker sidecar，不再为它单独修改 Universal**。插件自己在 ZIP 根目录声明 `host-manifest.json`，Universal 只维护一个通用 Host Supervisor。

宿主组件：

```text
/usr/local/lib/securex-plugin-host/securex_plugin_host.py
/etc/systemd/system/securex-plugin-host.service
/etc/systemd/system/securex-plugin-host.path
/etc/systemd/system/securex-plugin-host.timer
/var/lib/securex-plugin-host/state.json
```

工作流程：

```text
插件商城安装/升级
  ↓
/home/frigate/config/plugins/<id>/host-manifest.json 出现
  ↓
securex-plugin-host reconcile
  ↓
拉取镜像 / 创建 sidecar / 加入 Frigate network

配置改变
  ↓
重新计算 spec hash
  ↓
仅在参数变化时重建 sidecar

插件禁用/卸载
  ↓
自动删除对应 sidecar
  ↓
按 cleanup_on_remove 清理临时运行目录
```

### 6.1 host-manifest.json 示例

```json
{
  "schema_version": 1,
  "plugin_id": "tynvr_module_example",
  "config_file": "config.yml",
  "enabled_config_path": "enabled",
  "status_file": "host_status.json",
  "service": {
    "name": "securex-example",
    "image": "vendor/example:latest",
    "restart": "unless-stopped",
    "network": "frigate",
    "gpu": "auto_nvidia",
    "data_dirs": [
      {"path": "/home/frigate/config/example", "mode": "755"}
    ],
    "volumes": [
      {"source": "/home/frigate/config/example", "target": "/data", "mode": "rw"}
    ],
    "ports": [
      {
        "host_ip": "127.0.0.1",
        "host_port": 19000,
        "container_port": 9000,
        "protocol": "tcp"
      }
    ]
  },
  "cleanup_on_remove": []
}
```

### 6.2 支持的动态值

```text
${plugin_dir}
${config_dir}
${host.lan_ip}
${frigate.network}
${config.foo.bar}
${env.NAME}
```

`network: "frigate"` 会自动发现当前 Frigate Docker network；`network: "host"` 只在确实需要宿主网络时使用。

### 6.3 render_files

需要把插件生成的模板复制为宿主运行文件时：

```json
{
  "render_files": [
    {
      "source": "gateway.yaml",
      "destination": "/var/lib/securex-gb28181/config.yaml",
      "mode": "600",
      "replace": {
        "__SECUREX_HOST_LAN_IP__": "${host.lan_ip}"
      }
    }
  ]
}
```

### 6.4 安全边界

Generic Host Supervisor **不提供任意 root shell hook**。插件声明 Docker image、网络、端口、volume、env、GPU、device、持久目录和运行文件；宿主路径限制在 Securex 配置/运行目录以及受控 `/run/dbus`、`/dev` 范围。

`cleanup_on_remove` 只应该声明临时运行数据。模型、训练数据、历史记录等默认应保留。

## 7. 当前 Host 插件示例

- GB28181 Cameras v0.1.7：`host-manifest.json` 管理 `securex-gb28181`，动态读取 SIP/RTP 端口，卸载清理 `/var/lib/securex-gb28181`。
- Local AI Chat v0.1.5：`host-manifest.json` 管理 `securex-local-ai` / Ollama；模型目录 `/home/frigate/config/local_ai/ollama` 卸载时保留。
- Matter 当前继续使用已验证的兼容 supervisor；Fix69 不要求它立即迁移。

## 8. 数据与升级

- 插件代码：`/home/frigate/config/plugins/<plugin_id>/`
- 大型持久数据放独立目录，例如 `/home/frigate/config/local_ai/ollama`。
- 升级插件不得删除用户配置、模型、训练数据、录像和历史。
- 插件版本与 Store Catalog 版本必须同步。
- 如果插件新增 `host-manifest.json`，`min_tynvr_version` 至少应为 `1.9.88`。

## 9. 发布前检查

1. `manifest.json` JSON 校验通过。
2. Python `py_compile` 通过。
3. Shell `bash -n` 通过（如果有）。
4. ZIP 根目录正确，无 `__pycache__` / `.pyc`。
5. 简中 / 繁中 / English 无残留。
6. 主侧栏 key、icon、order 不冲突。
7. 安装、升级、禁用、卸载都回归。
8. Host 插件验证：安装自动启动；配置变化自动 reconcile；卸载自动删除 sidecar；持久数据策略正确。
9. Store `catalog.json`、package SHA256、首页版本、系统更新 manifest、开发文档同步。

## 10. Fix69 安装入口规则

从 Universal v1.9.92 Fix73 开始，Generic Plugin Host 的幂等安装位于 `install_tynvr_universal.py` 主入口，不再依赖外层 `install.sh`。因此 Fresh Installer、ISO First Boot、System Update / Host Updater 与手工安装行为一致。

- System Update Center 当前为 v1.0.34。
- Host Updater 当前为 v1.0.17。
- 新 Host 插件只需要 `host-manifest.json`；除非 Generic Host schema/framework 本身变化，否则不需要升级 Universal。
- 依赖 Generic Host 的新插件在 Store Catalog 中应声明 `min_tynvr_version >= 1.9.88`。


## Billiards current plugin

- Securex Billiards Recognition / Scoring v1.4.29：补齐运行时 Clear Table / 8-Ball 多语言。


## Fix71 SSH / RBAC

- Securex plugin navigation and direct plugin routes are administrator-only by default; members must not gain access by typing plugin URL/API directly.
- SSH Manager v0.1.0 requires Universal v1.9.92 Fix73 and uses controlled host actions only: `status`, `enable`, `disable`, `set_port`.
- Never expose an arbitrary root shell. Port changes must validate range/conflicts, run `sshd -t`, and roll back on failure.
- When the Universal baseline changes, synchronize Store catalog, System Update package/manifest, Fresh Installer/ISO payload, release history and developer docs.

## Fix72 / Fix73 插件设置兼容规则（2026-09-27）
- Fix72 起使用 Frigate 原生插件设置布局；存在侧栏控制或快捷操作时，不显示误导性的“没有可配置字段”。
- `navigation_user_toggle: true` 提供标准“侧栏显示”开关；隐藏侧栏不等于禁用插件。
- `actions[].label` 推荐标准字符串翻译键；Fix73 Universal 同时安全兼容多语言对象，避免 React 白屏。
- 管理员插件必须同时保护导航与直接 URL/API，前端隐藏不能替代后端 RBAC。
- 新 Universal 基线必须同步 System Update、Fresh Installer、offline-cache、ISO Build Kit、下载页、开发文档和实际 SHA256。

