# 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 Fix69

目前正式開發基線：Frigate v0.18.0；Universal v1.9.92 Fix73；System Update Center v1.0.34；Host Updater v1.0.17；Kiosk v0.3.9。

## 開發原則

- 優先透過 Universal Plugin API 擴充 Frigate，不重複 patch Frigate 核心。
- 一個功能一個外掛，獨立安裝、升級、停用、解除安裝。
- 一般設定使用 `config_apply: hot`；首次安裝或程式碼升級才允許一次重載。
- 大模型、訓練資料、錄影、快取、Secret 不要放在一般外掛 ZIP。

## Fix69 Generic Plugin Host Supervisor v1

Fix69 起，新外掛若需要宿主 Docker sidecar、連接埠、volume 或 GPU，**不需要再為每個外掛發布新的 Universal**。外掛在 ZIP 根目錄自行提供 `host-manifest.json`，Universal 只維護一套通用 Host Supervisor。

```text
商城安裝/升級 -> host-manifest 出現 -> reconcile -> 拉取/啟動 sidecar
設定變更      -> spec hash 改變      -> 必要時才重建
停用          -> 自動刪除 sidecar
解除安裝      -> 自動刪除 sidecar + 依聲明清理暫存執行資料
```

範例：

```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"}
    ]
  },
  "cleanup_on_remove": []
}
```

支援：`${plugin_dir}`、`${config_dir}`、`${host.lan_ip}`、`${frigate.network}`、`${config.foo.bar}`、`${env.NAME}`。

`network: "frigate"` 會自動加入目前 Frigate Docker network。`host-manifest` 為宣告式設定，不提供任意 root shell hook；宿主路徑限制在 Securex 設定/執行目錄與受控 `/run/dbus`、`/dev`。

## 目前範例

- GB28181 Cameras v0.1.7：透過 `host-manifest.json` 管理 `securex-gb28181`。
- Local AI Chat v0.1.5：透過 `host-manifest.json` 管理 Ollama；模型資料預設保留。
- Matter 本輪保留已驗證的相容 supervisor，之後可獨立遷移。

## 發布檢查

- JSON / Python / Shell 語法檢查。
- ZIP 不含 `__pycache__`、`.pyc`、Secret、測試資料。
- 簡中 / 繁中 / English 完整。
- Navigation key / icon / order 不衝突。
- 安裝、升級、停用、解除安裝完整回歸。
- Host 外掛驗證自動啟動、設定 reconcile、解除安裝清理與持久資料保留策略。
- Store Catalog、SHA256、首頁、System Update manifest、開發文件同步。
- 使用 `host-manifest.json` 的外掛，Store `min_tynvr_version` 至少設為 `1.9.88`。

## 10. Fix69 安裝入口規則

從 Universal v1.9.92 Fix73 開始，Generic Plugin Host 的冪等安裝位於 `install_tynvr_universal.py` 主入口。Fresh Installer、ISO First Boot、System Update / Host Updater 與手動安裝行為一致。System Update Center 目前為 v1.0.34，Host Updater 目前為 v1.0.17。新的 Host 外掛只需要 `host-manifest.json`，並應設定 `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。

