feat: Initial v0.9 release with API Key authentication

## v0.9.20260325_144654

### Features
- API Key Authentication System
- Job Worker System
- V2 Backup Versioning

### Bug Fixes
- get_processor_results_by_job column mapping

Co-authored-by: OpenCode
This commit is contained in:
accusys
2026-03-25 14:52:51 +08:00
parent 47e86b696f
commit 383201cacd
193 changed files with 40268 additions and 422 deletions

View File

@@ -0,0 +1,562 @@
# Momentry n8n 整合使用手冊
| 項目 | 內容 |
|------|------|
| 版本 | V1.1 |
| 日期 | 2026-03-23 |
| 目標讀者 | n8n 使用者、DevOps |
---
## 目錄
1. [概述](#1-概述)
2. [前置作業](#2-前置作業)
3. [建立 n8n API Key](#3-建立-n8n-api-key)
4. [在 n8n 中使用 Momentry API](#4-在-n8n-中使用-momentry-api)
5. [工作流範例](#5-工作流範例)
6. [常見問題](#6-常見問題)
---
## 1. 概述
### 1.1 什麼是 n8n
n8n 是一個開源的工作流自動化工具,可以連接各種服務和 API。
### 1.2 為什麼需要整合?
| 場景 | 說明 |
|------|------|
| 自動化影片處理 | 新影片上傳時自動觸發處理流程 |
| 監控告警 | API Key 異常時發送通知 |
| 定時備份 | 定期備份 API Key 資料 |
| 跨系統同步 | 與其他系統同步 API Key 狀態 |
### 1.3 架構圖
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 觸發器 │────▶│ n8n 工作流 │────▶│ Momentry │
│ (Webhook/ │ │ (處理邏輯) │ │ API │
│ Cron) │ └─────────────┘ └─────────────┘
└─────────────┘ │ │
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ 通知 │ │ 動作 │
│ (Slack/Email)│ │ (建立/查詢) │
└─────────────┘ └─────────────┘
```
---
### 1.4 API URL 選擇
| 環境 | URL | 說明 |
|------|-----|------|
| **本地測試** | `http://localhost:3002` | 直接訪問 API |
| **n8n workflow** | `https://api.momentry.ddns.net` | 通過反向代理 |
> ⚠️ **重要**: 在 n8n HTTP Request Node 中,請使用 `https://api.momentry.ddns.net` 而非 `localhost:3002`,因為 n8n 需要從外部訪問 API。
**本地測試時**:
```bash
curl http://localhost:3002/health
```
**n8n Workflow 中**:
```
URL: https://api.momentry.ddns.net/api/v1/n8n/search
```
---
## 2. 前置作業
### 2.1 確認服務狀態
```bash
# 檢查 Momentry API
curl http://localhost:3002/health
# 檢查 n8n
curl https://n8n.momentry.ddns.net/api/v1/workflows \
-H "X-N8N-API-KEY: your-api-key"
```
### 2.2 取得 n8n API Key
#### 方式 A: 透過 Momentry CLI
```bash
# 建立 n8n API Key
momentry n8n create \
--api-key "your-existing-n8n-api-key" \
--label "momentry-integration" \
--expires-in-days 90
# 輸出:
# ✅ n8n API Key created successfully!
# API Key: eyJhbGciOiJIUzI1NiIs...
```
#### 方式 B: 透過 n8n 介面
1. 登入 n8n: https://n8n.momentry.ddns.net
2. 前往 Settings → n8n API
3. 點擊「Create an API Key」
4. 複製 API Key
### 2.3 設定環境變數
在 n8n 中設定以下環境變數:
| 變數名稱 | 值 | 說明 |
|----------|-----|------|
| `MOMENTRY_API_URL` | `http://localhost:3002` | Momentry API URL |
| `MOMENTRY_API_KEY` | `your-api-key` | Momentry API Key |
---
## 3. 建立 n8n API Key
### 3.1 CLI 命令
```bash
# 基本建立
momentry n8n create \
--api-key <existing-n8n-key> \
--label <key-name>
# 設定過期時間
momentry n8n create \
--api-key <existing-n8n-key> \
--label "ci-pipeline" \
--expires-in-days 30
```
### 3.2 範例:建立監控用 Key
```bash
momentry n8n create \
--api-key "n8n_api_1234567890" \
--label "monitoring-key" \
--expires-in-days 180
# 輸出:
# ✅ n8n API Key created successfully!
# Key ID: abc123-def456
# Label: monitoring-key
# API Key: eyJhbGciOiJIUz...
```
### 3.3 列出已建立的 Key
```bash
momentry n8n list --api-key <existing-n8n-key>
# 輸出:
# 📋 n8n API Keys
# ┌────────────────────────────────────────────────────────────────────────────┐
# │ Label │ ID │
# ├────────────────────────────────────────────────────────────────────────────┤
# │ monitoring-key │ abc123-def456 │
# │ ci-pipeline │ xyz789-abc123 │
# └────────────────────────────────────────────────────────────────────────────┘
```
---
## 4. 在 n8n 中使用 Momentry API
> ⚠️ **注意**: API Key 管理端點 (`/api/v1/api-keys/*`) 目前仍在規劃中,尚未實作。以下為規劃中的 API 說明。
### 4.1 設定 HTTP Request 節點
```
Method: POST
URL: {{ $env.MOMENTRY_API_URL }}/api/v1/api-keys
Headers:
X-API-Key: {{ $env.MOMENTRY_API_KEY }}
Content-Type: application/json
Body:
{
"name": "auto-generated-key",
"key_type": "service",
"ttl_days": 90
}
```
### 4.2 可用的 API 端點
> ⚠️ **API Key 管理端點為規劃功能,目前尚未實作**
#### 已實作端點
| 方法 | 端點 | 說明 |
|------|------|------|
| GET | `/health` | 健康檢查 |
| POST | `/api/v1/search` | 語意搜尋 |
| POST | `/api/v1/n8n/search` | n8n 格式搜尋 |
| GET | `/api/v1/videos` | 列出所有影片 |
| GET | `/api/v1/lookup` | 查詢影片 |
| GET | `/api/v1/progress/:uuid` | 處理進度 |
#### 規劃中端點 *(尚未實作)*
| 方法 | 端點 | 說明 |
|------|------|------|
| GET | `/api/v1/api-keys` | 列出所有 API Keys |
| POST | `/api/v1/api-keys` | 建立新的 API Key |
| DELETE | `/api/v1/api-keys/{id}` | 刪除 API Key |
| POST | `/api/v1/api-keys/{id}/rotate` | 請求 Key 輪換 |
---
## 5. 工作流範例
### 範例 1定時檢查 API Key 狀態
**目的**: 每天早上 9 點檢查即將過期的 API Keys
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Schedule │────▶│ HTTP │────▶│ Filter │────▶│ Slack │
│ (每天 9AM) │ │ Request │ │ (7天內過期) │ │ 通知 │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
```
**HTTP Request 設定**:
```json
{
"method": "GET",
"url": "{{ $env.MOMENTRY_API_URL }}/api/v1/api-keys",
"headers": {
"X-API-Key": "{{ $env.MOMENTRY_API_KEY }}"
}
}
```
**Filter 設定**:
```javascript
// 檢查是否在 7 天內過期
const expiresAt = new Date($json.expires_at);
const now = new Date();
const sevenDaysLater = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
return expiresAt <= sevenDaysLater && expiresAt > now;
```
**Slack 通知格式**:
```
⚠️ API Key 即將過期提醒
以下 API Key 將在 7 天內過期:
{{ $json.map(k => `• ${k.name} (${k.key_id}) - 過期時間: ${k.expires_at}`).join('\n') }}
請及時處理!
```
---
### 範例 2新影片上傳時自動建立 API Key
**目的**: 當有新影片上傳時,自動為該影片建立專用 API Key
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Webhook │────▶│ HTTP │────▶│ Set │────▶│ Respond │
│ 觸發器 │ │ Request │ │ (組裝回應) │ │ Webhook │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
```
**Webhook 設定**:
```
Method: POST
Path: /new-video
```
**HTTP Request 設定**:
```json
{
"method": "POST",
"url": "{{ $env.MOMENTRY_API_URL }}/api/v1/api-keys",
"headers": {
"X-API-Key": "{{ $env.MOMENTRY_API_KEY }}"
},
"body": {
"name": "video-{{ $json.video_id }}",
"key_type": "service",
"permissions": ["read"],
"ttl_days": 30
}
}
```
**回應格式**:
```json
{
"success": true,
"video_id": "{{ $json.video_id }}",
"api_key_id": "{{ $json.key_id }}",
"message": "API Key 已建立"
}
```
---
### 範例 3API Key 異常告警
**目的**: 監控 API Key 異常使用,發送告警通知
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Webhook │────▶│ Switch │────▶│ Email │ │ Slack │
│ (異常通知) │ │ (嚴重程度) │────▶│ 通知 │ │ 通知 │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
```
**Webhook 觸發設定** (在 Momentry 中):
```bash
export WEBHOOK_URL="https://n8n.momentry.ddns.net/webhook/anomaly-alert"
export WEBHOOK_EVENTS="anomaly_detected,rate_limited,ip_blocked"
```
**Switch 節點設定**:
```javascript
// 根據嚴重程度分流
switch ($json.data.severity) {
case 'critical':
return 0; // Email + Slack
case 'high':
return 1; // Slack only
default:
return 2; // Log only
}
```
**Email 通知格式**:
```
Subject: [{{ $json.data.severity }}] API Key 異常告警 - {{ $json.data.key_id }}
Dear Admin,
偵測到 API Key 異常使用:
Key ID: {{ $json.data.key_id }}
異常類型: {{ $json.data.anomaly_type }}
嚴重程度: {{ $json.data.severity }}
時間: {{ $json.timestamp }}
請立即檢查系統狀態。
Best regards,
Momentry Monitoring
```
---
### 範例 4定時備份 API Key 統計
**目的**: 每週一早上備份 API Key 統計報表
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Schedule │────▶│ HTTP │────▶│ Google │
│ (每週一) │ │ Request │ │ Sheets │
└─────────────┘ └─────────────┘ └─────────────┘
```
**HTTP Request 設定**:
```json
{
"method": "GET",
"url": "{{ $env.MOMENTRY_API_URL }}/api/v1/api-keys/stats",
"headers": {
"X-API-Key": "{{ $env.MOMENTRY_API_KEY }}"
}
}
```
**Google Sheets 設定**:
```
Spreadsheet: Momentry API Key Reports
Sheet: Weekly Stats
Append Row:
- Date: {{ $now }}
- Total Keys: {{ $json.total_keys }}
- Active Keys: {{ $json.active_keys }}
- Expired Keys: {{ $json.expired_keys }}
- Anomalies (24h): {{ $json.anomalies_last_24h }}
```
---
### 範例 5自動輪換即將過期的 Key
**目的**: 自動為即將過期的 Key 請求輪換
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Schedule │────▶│ HTTP │────▶│ Filter │────▶│ HTTP │
│ (每天) │ │ (取得 Keys) │ │ (即將過期) │ │ (請求輪換) │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
```
**第一個 HTTP Request (取得 Keys)**:
```json
{
"method": "GET",
"url": "{{ $env.MOMENTRY_API_URL }}/api/v1/api-keys",
"headers": {
"X-API-Key": "{{ $env.MOMENTRY_API_KEY }}"
}
}
```
**Filter 設定**:
```javascript
// 14 天內過期且未請求輪換的 Key
const expiresAt = new Date($json.expires_at);
const now = new Date();
const fourteenDaysLater = new Date(now.getTime() + 14 * 24 * 60 * 60 * 1000);
return expiresAt <= fourteenDaysLater &&
!$json.rotation_required &&
$json.status === 'active';
```
**第二個 HTTP Request (請求輪換)**:
```json
{
"method": "POST",
"url": "{{ $env.MOMENTRY_API_URL }}/api/v1/api-keys/{{ $json.key_id }}/rotate",
"headers": {
"X-API-Key": "{{ $env.MOMENTRY_API_KEY }}"
},
"body": {
"reason": "auto_rotation_approaching_expiry"
}
}
```
---
## 6. 常見問題
### Q1: n8n 無法連接到 Momentry API
**檢查項目**:
```bash
# 1. 確認 API 是否運行
curl http://localhost:3002/health
# 2. 確認 API Key 是否有效
momentry api-key validate --key "your-key"
# 3. 檢查防火牆設定
nc -zv localhost 3002
```
### Q2: API Key 建立失敗
**可能原因**:
- API Key 已存在
- 權限不足
- 格式錯誤
**解決方式**:
```bash
# 檢查現有 Keys
momentry api-key list
# 使用不同的 label
momentry n8n create --api-key "..." --label "unique-label-$(date +%s)"
```
### Q3: Webhook 通知沒有收到
**檢查項目**:
```bash
# 1. 確認 Webhook URL 設定
echo $WEBHOOK_URL
# 2. 測試 Webhook
curl -X POST $WEBHOOK_URL \
-H "Content-Type: application/json" \
-d '{"test": true}'
# 3. 檢查 n8n 工作流是否啟用
# 登入 n8n → 檢查工作流狀態
```
### Q4: 如何撤銷 n8n API Key
```bash
# 列出所有 Keys
momentry n8n list --api-key "your-admin-key"
# 刪除指定 Key
momentry n8n delete \
--api-key "your-admin-key" \
--label "key-to-delete"
```
---
## 附錄
### A. n8n 工作流匯出
將上述範例工作流匯入 n8n
1. 複製工作流 JSON
2. 登入 n8n
3. 點擊「+」→「Import from File」
4. 貼上 JSON 並儲存
### B. 環境變數總覽
```bash
# Momentry
MOMENTRY_API_URL=http://localhost:3002
MOMENTRY_API_KEY=your-api-key
# n8n
N8N_URL=https://n8n.momentry.ddns.net
N8N_API_KEY=your-n8n-api-key
# Webhook
WEBHOOK_URL=https://n8n.momentry.ddns.net/webhook/alerts
WEBHOOK_SECRET=your-secret
WEBHOOK_EVENTS=anomaly_detected,key_expired,key_revoked
```
### C. 相關文件
| 文件 | 說明 |
|------|------|
| [API_INDEX.md](./API_INDEX.md) | 文件總覽(起點) |
| [API_N8N_GUIDE.md](./API_N8N_GUIDE.md) | n8n 快速使用指南 |
| `docs/API_KEY_MANAGEMENT.md` | API Key 管理系統設計 |
| `docs/API_KEY_ARCHITECTURE.md` | 系統架構圖 |
| `docs/API_KEY_INTEGRATION_TESTS.md` | 整合測試文件 |