feat(frontend): enhance webhook functionality and UI

- Updated incoming webhook API endpoint to use `/api/webhook/post/<name>` for better namespace management.
- Added a new WebHooks page in the admin UI for managing webhook endpoints.
- Introduced a ConfigSection component to streamline the rendering and saving of configuration fields.
- Enhanced Settings.vue to reference the new WebHooks page and updated the configuration structure.
- Implemented a new webhook API in the frontend to handle listing, adding, modifying, and removing webhook endpoints.
- Improved the sidebar to include a link to the WebHooks page.
- Added functionality to generate tokens for new webhook endpoints and manage notification channels.
This commit is contained in:
2026-09-24 15:02:52 +08:00
parent 3877c6d128
commit f36f17bd2a
7 changed files with 752 additions and 201 deletions
+10 -7
View File
@@ -11,12 +11,12 @@ Nukumizu connects to a Komari Dashboard instance, keeps an in-memory view of eve
- **Remote command execution** — dispatches commands through the Komari task API and polls the result (1s interval, up to 60s timeout). - **Remote command execution** — dispatches commands through the Komari task API and polls the result (1s interval, up to 60s timeout).
- **Interactive bots** — QQ (NapCat / OneBot 11) and Telegram bots for `/list`, `/status`, `/info`, `/run`, `/shutdown`, `/reboot`, and more, protected by an admin / trusted-group permission model. - **Interactive bots** — QQ (NapCat / OneBot 11) and Telegram bots for `/list`, `/status`, `/info`, `/run`, `/shutdown`, `/reboot`, and more, protected by an admin / trusted-group permission model.
- **Notification channels** — server status changes are pushed to every enabled channel: QQ, Telegram, Email (SMTP), [ntfy](https://ntfy.sh), and Webhook. - **Notification channels** — server status changes are pushed to every enabled channel: QQ, Telegram, Email (SMTP), [ntfy](https://ntfy.sh), and Webhook.
- **Incoming webhook API** — external applications can push their own alerts in via `POST /api/webhook/<name>`, and Nukumizu relays them to the channels that endpoint lists. Each endpoint carries its own token and target channels, and the API is served on a **separate listener** so it can be exposed without exposing the admin API. - **Incoming webhook API** — external applications can push their own alerts in via `POST /api/webhook/post/<name>`, and Nukumizu relays them to the channels that endpoint lists. Each endpoint carries its own token and target channels, and the API is served on a **separate listener** so it can be exposed without exposing the admin API.
- **Network proxy** — a global proxy URL can be enabled per controller (`networkUseProxy`) for HTTP, WebSocket, and even SMTP (HTTP CONNECT tunnel). - **Network proxy** — a global proxy URL can be enabled per controller (`networkUseProxy`) for HTTP, WebSocket, and even SMTP (HTTP CONNECT tunnel).
- **Customizable message templates** — every bot/notification message is rendered from a template in `config.json`, with Markdown formatting switched on per channel. - **Customizable message templates** — every bot/notification message is rendered from a template in `config.json`, with Markdown formatting switched on per channel.
- **Storage** — SQLite (pure-Go driver) for `user.db` and `log.db`; safe on network shares (WAL disabled). - **Storage** — SQLite (pure-Go driver) for `user.db` and `log.db`; safe on network shares (WAL disabled).
- **Dashboard API** — token-authenticated REST API plus an admin-only live log-streaming WebSocket. - **Dashboard API** — token-authenticated REST API plus an admin-only live log-streaming WebSocket.
- **Web console** — a Vue 3 admin UI for browsing nodes, editing `config.json`, managing bot trust, and tailing logs. The built bundle is embedded in the binary, so a single executable serves both the API and the console. - **Web console** — a Vue 3 admin UI for browsing nodes, editing `config.json`, managing bot trust and webhook endpoints, and tailing logs. The built bundle is embedded in the binary, so a single executable serves both the API and the console.
## How it works ## How it works
@@ -41,7 +41,8 @@ nukumizu-backend/
│ ├── user.go # /api/user/login, /api/user/register │ ├── user.go # /api/user/login, /api/user/register
│ ├── server.go # /api/server/list, getInfo, getStatus, exec │ ├── server.go # /api/server/list, getInfo, getStatus, exec
│ ├── settings.go # /api/settings/get, set │ ├── settings.go # /api/settings/get, set
│ ├── webhook.go # /api/webhook/{name} (incoming webhook API) │ ├── webhook.go # /api/webhook/post/{name} (incoming webhook API)
│ ├── webhook_endpoints.go # /api/webhook/add, modify, delete, list
│ └── health.go # /health │ └── health.go # /health
├── database/ ├── database/
│ └── user.go # user.db (SQLite) user store │ └── user.go # user.db (SQLite) user store
@@ -91,8 +92,8 @@ nukumizu-backend/
├── api/index.js # Wrappers around the REST endpoints ├── api/index.js # Wrappers around the REST endpoints
├── router/index.js # Routes and the login guard ├── router/index.js # Routes and the login guard
├── utils/ # http/auth/theme/toast/format/runtime helpers ├── utils/ # http/auth/theme/toast/format/runtime helpers
├── components/ # Modal, Toggle, editors, top bar, side bar ├── components/ # Modal, Toggle, editors, ConfigSection, top bar, side bar
└── views/ # Login, Overview, Trusted, Settings, Logs └── views/ # Login, Overview, Trusted, Settings, WebHooks, Logs
``` ```
## Requirements ## Requirements
@@ -340,11 +341,13 @@ Middleware applied to the whole server:
A listener of its own, so external applications can be pointed at it without being able to reach the admin API. It is switched on with `webhook.enabled` and binds `webhook.listenAddr:webhook.listenPort` (default `0.0.0.0:8081`); that half of the configuration is applied at startup, while `webhook.endpoints` is re-read whenever the config is reloaded. Only the rate limit and CORS middleware apply here — no session token is involved. A listener of its own, so external applications can be pointed at it without being able to reach the admin API. It is switched on with `webhook.enabled` and binds `webhook.listenAddr:webhook.listenPort` (default `0.0.0.0:8081`); that half of the configuration is applied at startup, while `webhook.endpoints` is re-read whenever the config is reloaded. Only the rate limit and CORS middleware apply here — no session token is involved.
The console's **WebHooks** page manages the listener settings and the endpoints. The outgoing WebHook notification channel (`controllerMethod.webhook`) stays on the Settings page with the other notification channels, since it is one of them.
| Endpoint | Method | Permission | Description | | Endpoint | Method | Permission | Description |
|---|---|---|---| |---|---|---|---|
| `/api/webhook/<name>` | POST | Endpoint token | Relay an alert to the channels the endpoint lists in `notifyPipes`. Body `{token, subject, content}`. Returns `data: {endpoint, channels}`. | | `/api/webhook/post/<name>` | POST | Endpoint token | Relay an alert to the channels the endpoint lists in `notifyPipes`. Body `{token, subject, content}`. Returns `data: {endpoint, channels}`. |
Every entry under `webhook.endpoints` is one endpoint, addressed by its key as the last path segment: the key `example` is served at `POST /api/webhook/example`. Endpoints are managed over the admin API (`/api/webhook/add`, `modify`, `delete` and `list` — see [Endpoints](#endpoints)), which writes the same `webhook.endpoints` section of `config.json`; a newly added endpoint accepts requests as soon as the configuration is reloaded, without a restart. An endpoint holds: Every entry under `webhook.endpoints` is one endpoint, addressed by its key as the last path segment: the key `example` is served at `POST /api/webhook/post/example`. The `post/` segment keeps the endpoints' own namespace separate from the management routes (`/api/webhook/add` and friends), which live on the admin listener. Endpoints are managed over the admin API (`/api/webhook/add`, `modify`, `delete` and `list` — see [Endpoints](#endpoints)), which writes the same `webhook.endpoints` section of `config.json`; a newly added endpoint accepts requests as soon as the configuration is reloaded, without a restart. An endpoint holds:
| Field | Meaning | | Field | Meaning |
|---|---| |---|---|
+13
View File
@@ -19,3 +19,16 @@ export const settingsApi = {
get: (type) => http.get(`/settings/get?type=${encodeURIComponent(type)}`), get: (type) => http.get(`/settings/get?type=${encodeURIComponent(type)}`),
set: (type, patch) => http.post(`/settings/set?type=${encodeURIComponent(type)}`, patch) set: (type, patch) => http.post(`/settings/set?type=${encodeURIComponent(type)}`, patch)
}; };
// Incoming webhook endpoints (admin). They live in the `webhook.endpoints`
// section of config.json, but are managed here rather than through the settings
// API because they are a keyed collection: add/modify take one endpoint object
// and change only the fields they carry, and a new endpoint is rejected with
// 409 when its name is taken.
// list → { success, message, data: { endpoints: { "<name>": { enabled, token, notifyPipes } } } }.
export const webhookApi = {
list: () => http.get('/webhook/list'),
add: (endpoint) => http.post('/webhook/add', endpoint),
modify: (endpoint) => http.post('/webhook/modify', endpoint),
remove: (name) => http.post('/webhook/delete', { name })
};
+228
View File
@@ -0,0 +1,228 @@
<script setup>
import { reactive, ref, watch } from 'vue';
import { settingsApi } from '../api/index.js';
import { debugMode } from '../utils/runtime.js';
import { toast } from '../utils/toast.js';
import Toggle from './Toggle.vue';
import TagsEditor from './TagsEditor.vue';
import HeadersEditor from './HeadersEditor.vue';
// One card of the global config.json: it renders the fields a section
// descriptor declares and saves exactly those fields, leaving every other key
// of the file untouched. Settings.vue and WebHooks.vue both compose this
// component, which is why the descriptor (not the config layout) is what a view
// supplies here.
//
// A descriptor is:
// id unique key of the section, used for logging
// title card heading
// hint optional line under the heading
// root path in config.json the fields live under, e.g. ['controllerMethod', 'ntfy']
// fields [{ key, type, label, ... }], where type is one of
// bool | text | password | number | select | textarea | tags | headers
// - `lp` overrides the field key with an explicit path inside root
// - `options` lists the choices of a select, `placeholder`/`help` are
// passed through to the input
const props = defineProps({
section: { type: Object, required: true },
config: { type: Object, default: () => ({}) }
});
const emit = defineEmits(['saved']);
const vals = ref({});
const saving = ref(false);
function fieldPath(f) {
return f.lp || [f.key];
}
function getVal(obj, path, fb) {
let cur = obj;
for (const k of path) {
if (cur === null || cur === undefined || typeof cur !== 'object') return fb;
cur = cur[k];
}
return cur === undefined || cur === null ? fb : cur;
}
// hasVal reports whether a path actually resolves in the loaded config. A
// missing key and a key whose value equals the fallback are indistinguishable
// from getVal's return value alone, so misses are detected separately.
function hasVal(obj, path) {
let cur = obj;
for (const k of path) {
if (cur === null || cur === undefined || typeof cur !== 'object') return false;
cur = cur[k];
}
return cur !== undefined && cur !== null;
}
function defaults(f) {
switch (f.type) {
case 'bool': return false;
case 'number': return 0;
case 'tags': return [];
case 'headers': return {};
default: return '';
}
}
// Mirror wrapRoot() on save: prepend the section's root path so a value is read
// from the same place it is written to.
function read() {
const obj = {};
for (const f of props.section.fields) {
const path = [...props.section.root, ...fieldPath(f)];
obj[f.key] = getVal(props.config, path, defaults(f));
if (debugMode.value) {
console.log(`[ConfigSection] Loaded ${props.section.id}.${f.key}:`, obj[f.key]);
if (!hasVal(props.config, path)) {
console.warn(`[ConfigSection] ${props.section.id}.${f.key} missing at "${path.join('.')}" — using default`);
}
}
}
vals.value = obj;
}
function normalize(f, v) {
switch (f.type) {
case 'number': {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
}
case 'tags': return Array.isArray(v) ? v : [];
case 'headers': return v && typeof v === 'object' ? v : {};
default: return v === null || v === undefined ? '' : v;
}
}
function nest(obj) {
const out = {};
for (const [k, v] of Object.entries(obj)) {
const path = k.split('.');
let o = out;
for (let i = 0; i < path.length - 1; i += 1) {
const seg = path[i];
if (!o[seg]) o[seg] = {};
o = o[seg];
}
o[path[path.length - 1]] = v;
}
return out;
}
function wrapRoot(section, obj) {
const root = section.root;
if (!root.length) return obj;
const out = {};
let o = out;
for (let i = 0; i < root.length - 1; i += 1) {
o[root[i]] = {};
o = o[root[i]];
}
o[root[root.length - 1]] = obj;
return out;
}
async function save() {
const obj = {};
for (const f of props.section.fields) {
obj[f.key] = normalize(f, vals.value[f.key]);
}
const patch = wrapRoot(props.section, nest(obj));
saving.value = true;
try {
await settingsApi.set('global', patch);
toast.success(`${props.section.title} saved`);
emit('saved');
} catch (e) {
toast.error('Failed to save: ' + e.message);
} finally {
saving.value = false;
}
}
// Re-read whenever the caller reloads the configuration, so the card always
// shows what the file holds.
watch(() => props.config, read, { immediate: true });
</script>
<template>
<div class="card">
<div class="card-head">
<div>
<h3>{{ section.title }}</h3>
<p v-if="section.hint" class="hint">{{ section.hint }}</p>
</div>
<button class="btn btn-primary btn-sm" :disabled="saving" @click="save">
<span v-if="saving" class="spinner" style="width:12px;height:12px" />
<i v-else class="fas fa-check" /> Save
</button>
</div>
<div class="card-body">
<div class="form-grid">
<template v-for="f in section.fields" :key="f.key">
<div v-if="f.type === 'bool'" class="bool-cell">
<Toggle :model-value="vals[f.key]" :label="f.label" @update:model-value="vals[f.key] = $event" />
<p v-if="f.help" class="field-help">{{ f.help }}</p>
</div>
<div v-else-if="f.type === 'tags'" class="field span-2">
<label>{{ f.label }}</label>
<TagsEditor v-model="vals[f.key]" :placeholder="f.placeholder" />
</div>
<div v-else-if="f.type === 'headers'" class="field span-2">
<label>{{ f.label }}</label>
<HeadersEditor v-model="vals[f.key]" />
</div>
<div v-else class="field span-2">
<label>{{ f.label }}</label>
<textarea
v-if="f.type === 'textarea'"
v-model="vals[f.key]"
class="textarea"
rows="4"
spellcheck="false"
/>
<select
v-else-if="f.type === 'select'"
v-model="vals[f.key]"
class="select"
>
<option v-for="opt in f.options" :key="opt" :value="opt">{{ opt }}</option>
</select>
<input
v-else
v-model="vals[f.key]"
class="input"
:type="f.type === 'password' ? 'password' : 'text'"
:placeholder="f.placeholder || ''"
autocomplete="off"
spellcheck="false"
/>
</div>
</template>
</div>
</div>
</div>
</template>
<style scoped>
.bool-cell {
display: flex;
flex-direction: column;
gap: 3px;
padding: 8px 0;
}
.field-help {
font-size: 12px;
color: var(--text-3);
padding-left: 50px;
max-width: 340px;
}
</style>
+1
View File
@@ -11,6 +11,7 @@ const groups = [
label: 'System', label: 'System',
items: [ items: [
{ name: 'Settings', to: '/settings', title: 'Settings', icon: 'fa-sliders' }, { name: 'Settings', to: '/settings', title: 'Settings', icon: 'fa-sliders' },
{ name: 'WebHooks', to: '/webhooks', title: 'WebHooks', icon: 'fa-satellite-dish' },
{ name: 'Logs', to: '/logs', title: 'Logs', icon: 'fa-terminal' } { name: 'Logs', to: '/logs', title: 'Logs', icon: 'fa-terminal' }
] ]
} }
+6
View File
@@ -31,6 +31,12 @@ const routes = [
component: () => import('../views/Settings.vue'), component: () => import('../views/Settings.vue'),
meta: { title: 'Settings' } meta: { title: 'Settings' }
}, },
{
path: 'webhooks',
name: 'WebHooks',
component: () => import('../views/WebHooks.vue'),
meta: { title: 'WebHooks' }
},
{ {
path: 'logs', path: 'logs',
name: 'Logs', name: 'Logs',
+14 -194
View File
@@ -1,12 +1,12 @@
<script setup> <script setup>
import { onMounted, reactive, ref } from 'vue'; import { onMounted, ref } from 'vue';
import { settingsApi } from '../api/index.js'; import { settingsApi } from '../api/index.js';
import { debugMode } from '../utils/runtime.js';
import { toast } from '../utils/toast.js'; import { toast } from '../utils/toast.js';
import Toggle from '../components/Toggle.vue'; import ConfigSection from '../components/ConfigSection.vue';
import TagsEditor from '../components/TagsEditor.vue';
import HeadersEditor from '../components/HeadersEditor.vue';
// Every section is rendered and saved by ConfigSection, which owns the
// field-descriptor format. The incoming webhook API has its own page (see
// WebHooks.vue) and is not listed here.
const sections = [ const sections = [
{ {
id: 'system', id: 'system',
@@ -65,6 +65,7 @@ const sections = [
root: ['controllerMethod', 'qq(napcat)'], root: ['controllerMethod', 'qq(napcat)'],
fields: [ fields: [
{ key: 'enabled', type: 'bool', label: 'Enabled' }, { key: 'enabled', type: 'bool', label: 'Enabled' },
{ key: 'markdown', type: 'bool', label: 'Markdown', help: 'Send the formatted variant of the templates (code blocks, inline code).' },
{ key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' }, { key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' },
{ key: 'napcatAddr', type: 'text', label: 'NapCat address' }, { key: 'napcatAddr', type: 'text', label: 'NapCat address' },
{ key: 'napcatPort', type: 'text', label: 'NapCat port' }, { key: 'napcatPort', type: 'text', label: 'NapCat port' },
@@ -79,6 +80,7 @@ const sections = [
root: ['controllerMethod', 'telegram'], root: ['controllerMethod', 'telegram'],
fields: [ fields: [
{ key: 'enabled', type: 'bool', label: 'Enabled' }, { key: 'enabled', type: 'bool', label: 'Enabled' },
{ key: 'markdown', type: 'bool', label: 'Markdown', help: 'Sends messages with parse_mode=Markdown; turn off to have text delivered verbatim.' },
{ key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' }, { key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' },
{ key: 'botToken', type: 'password', label: 'Bot token' }, { key: 'botToken', type: 'password', label: 'Bot token' },
{ key: 'listenMethod', type: 'select', label: 'Listen method', options: ['global', 'at'] } { key: 'listenMethod', type: 'select', label: 'Listen method', options: ['global', 'at'] }
@@ -90,6 +92,7 @@ const sections = [
root: ['controllerMethod', 'email'], root: ['controllerMethod', 'email'],
fields: [ fields: [
{ key: 'enabled', type: 'bool', label: 'Enabled' }, { key: 'enabled', type: 'bool', label: 'Enabled' },
{ key: 'markdown', type: 'bool', label: 'Markdown', help: 'Send the formatted variant of the templates (code blocks, inline code).' },
{ key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' }, { key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' },
{ key: 'smtpHost', type: 'text', label: 'SMTP host' }, { key: 'smtpHost', type: 'text', label: 'SMTP host' },
{ key: 'smtpPort', type: 'number', label: 'SMTP port' }, { key: 'smtpPort', type: 'number', label: 'SMTP port' },
@@ -106,6 +109,7 @@ const sections = [
root: ['controllerMethod', 'ntfy'], root: ['controllerMethod', 'ntfy'],
fields: [ fields: [
{ key: 'enabled', type: 'bool', label: 'Enabled' }, { key: 'enabled', type: 'bool', label: 'Enabled' },
{ key: 'markdown', type: 'bool', label: 'Markdown', help: 'Send the formatted variant of the templates (code blocks, inline code).' },
{ key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' }, { key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' },
{ key: 'server', type: 'text', label: 'Server' }, { key: 'server', type: 'text', label: 'Server' },
{ key: 'topic', type: 'text', label: 'Topic' }, { key: 'topic', type: 'text', label: 'Topic' },
@@ -116,9 +120,11 @@ const sections = [
{ {
id: 'webhook', id: 'webhook',
title: 'Webhook notifications', title: 'Webhook notifications',
hint: 'Where this program posts its own alerts. The incoming webhook API has its own page (see WebHooks).',
root: ['controllerMethod', 'webhook'], root: ['controllerMethod', 'webhook'],
fields: [ fields: [
{ key: 'enabled', type: 'bool', label: 'Enabled' }, { key: 'enabled', type: 'bool', label: 'Enabled' },
{ key: 'markdown', type: 'bool', label: 'Markdown', help: 'Format the alert body with code blocks and inline code in the posted payload.' },
{ key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' }, { key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' },
{ key: 'url', type: 'text', label: 'URL' }, { key: 'url', type: 'text', label: 'URL' },
{ key: 'method', type: 'select', label: 'Method', options: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] }, { key: 'method', type: 'select', label: 'Method', options: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },
@@ -140,64 +146,12 @@ const sections = [
const loading = ref(true); const loading = ref(true);
const failed = ref(false); const failed = ref(false);
const vals = reactive({}); const cfg = ref({});
const saving = reactive(new Set());
function fieldPath(f) {
return f.lp || [f.key];
}
function getVal(obj, path, fb) {
let cur = obj;
for (const k of path) {
if (cur === null || cur === undefined || typeof cur !== 'object') return fb;
cur = cur[k];
}
return cur === undefined || cur === null ? fb : cur;
}
// hasVal reports whether a path actually resolves in the loaded config. A
// missing key and a key whose value equals the fallback are indistinguishable
// from getVal's return value alone, so misses are detected separately.
function hasVal(obj, path) {
let cur = obj;
for (const k of path) {
if (cur === null || cur === undefined || typeof cur !== 'object') return false;
cur = cur[k];
}
return cur !== undefined && cur !== null;
}
function defaults(f) {
switch (f.type) {
case 'bool': return false;
case 'number': return 0;
case 'tags': return [];
case 'headers': return {};
default: return '';
}
}
async function load() { async function load() {
try { try {
const res = await settingsApi.get('global'); const res = await settingsApi.get('global');
const cfg = (res && res.data && res.data.config) || {}; cfg.value = (res && res.data && res.data.config) || {};
for (const s of sections) {
const obj = {};
for (const f of s.fields) {
// Mirror wrapRoot() on save: prepend the section's root path so
// the value is read from the same place it is written to.
const path = [...s.root, ...fieldPath(f)];
obj[f.key] = getVal(cfg, path, defaults(f));
if (debugMode.value) {
console.log(`[Settings] Loaded ${s.id}.${f.key}:`, obj[f.key]);
if (!hasVal(cfg, path)) {
console.warn(`[Settings] ${s.id}.${f.key} missing at "${path.join('.')}" — using default`);
}
}
}
vals[s.id] = obj;
}
failed.value = false; failed.value = false;
} catch (e) { } catch (e) {
failed.value = true; failed.value = true;
@@ -207,65 +161,6 @@ async function load() {
} }
} }
function normalize(f, v) {
switch (f.type) {
case 'number': {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
}
case 'tags': return Array.isArray(v) ? v : [];
case 'headers': return v && typeof v === 'object' ? v : {};
default: return v === null || v === undefined ? '' : v;
}
}
function nest(obj) {
const out = {};
for (const [k, v] of Object.entries(obj)) {
const path = k.split('.');
let o = out;
for (let i = 0; i < path.length - 1; i += 1) {
const seg = path[i];
if (!o[seg]) o[seg] = {};
o = o[seg];
}
o[path[path.length - 1]] = v;
}
return out;
}
function wrapRoot(section, obj) {
const root = section.root;
if (!root.length) return obj;
const out = {};
let o = out;
for (let i = 0; i < root.length - 1; i += 1) {
o[root[i]] = {};
o = o[root[i]];
}
o[root[root.length - 1]] = obj;
return out;
}
async function save(section) {
const source = vals[section.id];
const obj = {};
for (const f of section.fields) {
obj[f.key] = normalize(f, source[f.key]);
}
const patch = wrapRoot(section, nest(obj));
saving.add(section.id);
try {
await settingsApi.set('global', patch);
toast.success(`${section.title} saved`);
await load();
} catch (e) {
toast.error('Failed to save: ' + e.message);
} finally {
saving.delete(section.id);
}
}
onMounted(load); onMounted(load);
</script> </script>
@@ -291,82 +186,7 @@ onMounted(load);
<div v-else-if="loading" class="card empty"><span class="spinner" /></div> <div v-else-if="loading" class="card empty"><span class="spinner" /></div>
<div v-else> <div v-else>
<div v-for="s in sections" :key="s.id" class="card"> <ConfigSection v-for="s in sections" :key="s.id" :section="s" :config="cfg" @saved="load" />
<div class="card-head">
<div>
<h3>{{ s.title }}</h3>
<p v-if="s.hint" class="hint">{{ s.hint }}</p>
</div>
<button class="btn btn-primary btn-sm" :disabled="saving.has(s.id)" @click="save(s)">
<span v-if="saving.has(s.id)" class="spinner" style="width:12px;height:12px" />
<i v-else class="fas fa-check" /> Save
</button>
</div>
<div class="card-body">
<div class="form-grid">
<template v-for="f in s.fields" :key="f.key">
<div v-if="f.type === 'bool'" class="bool-cell">
<Toggle :model-value="vals[s.id][f.key]" :label="f.label" @update:model-value="vals[s.id][f.key] = $event" />
<p v-if="f.help" class="field-help">{{ f.help }}</p>
</div>
<div v-else-if="f.type === 'tags'" class="field span-2">
<label>{{ f.label }}</label>
<TagsEditor v-model="vals[s.id][f.key]" :placeholder="f.placeholder" />
</div>
<div v-else-if="f.type === 'headers'" class="field span-2">
<label>{{ f.label }}</label>
<HeadersEditor v-model="vals[s.id][f.key]" />
</div>
<div v-else class="field span-2">
<label>{{ f.label }}</label>
<textarea
v-if="f.type === 'textarea'"
v-model="vals[s.id][f.key]"
class="textarea"
rows="4"
spellcheck="false"
/>
<select
v-else-if="f.type === 'select'"
v-model="vals[s.id][f.key]"
class="select"
>
<option v-for="opt in f.options" :key="opt" :value="opt">{{ opt }}</option>
</select>
<input
v-else
v-model="vals[s.id][f.key]"
class="input"
:type="f.type === 'password' ? 'password' : 'text'"
:placeholder="f.placeholder || ''"
autocomplete="off"
spellcheck="false"
/>
</div>
</template>
</div>
</div>
</div>
</div> </div>
</section> </section>
</template> </template>
<style scoped>
.bool-cell {
display: flex;
flex-direction: column;
gap: 3px;
padding: 8px 0;
}
.field-help {
font-size: 12px;
color: var(--text-3);
padding-left: 50px;
max-width: 340px;
}
</style>
+480
View File
@@ -0,0 +1,480 @@
<script setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { settingsApi, webhookApi } from '../api/index.js';
import { toast } from '../utils/toast.js';
import ConfigSection from '../components/ConfigSection.vue';
import Toggle from '../components/Toggle.vue';
import Modal from '../components/Modal.vue';
// The notification channels an endpoint may relay to. These mirror the
// controller names in config.json (controllerMethod.*), which is exactly what
// the backend matches notifyPipes against.
const CHANNELS = [
{ key: 'qq(napcat)', label: 'QQ' },
{ key: 'telegram', label: 'Telegram' },
{ key: 'email', label: 'Email' },
{ key: 'ntfy', label: 'ntfy' },
{ key: 'webhook', label: 'WebHook' }
];
// The listener half of the incoming webhook API. The endpoints it serves are
// managed through /api/webhook/* instead of the settings API, because they are
// a keyed collection rather than a fixed set of fields. The outgoing WebHook
// notification channel stays on the Settings page with the other channels.
const apiSection = {
id: 'webhookApi',
title: 'Incoming API',
hint: 'Listener external applications post to. The address and port are read at startup — changing them needs a restart.',
root: ['webhook'],
fields: [
{ key: 'enabled', type: 'bool', label: 'Enabled', help: 'Disabled means no listener is started at all.' },
{ key: 'listenAddr', type: 'text', label: 'Listen address' },
{ key: 'listenPort', type: 'text', label: 'Listen port' }
]
};
const loading = ref(true);
const failed = ref(false);
const cfg = ref({});
const endpoints = ref([]);
const saving = reactive(new Set());
const revealed = reactive(new Set());
const editor = reactive({ open: false, mode: 'add', name: '', token: '', pipes: [] });
const removing = reactive({ open: false, name: '' });
const channelLabel = (key) => (CHANNELS.find((c) => c.key === key) || { label: key }).label;
// Endpoint URLs are on the webhook listener, not the one serving this console,
// so the host is taken from the browser and the port from the configuration.
const listenPort = computed(() => (cfg.value.webhook && cfg.value.webhook.listenPort) || '8081');
const endpointURL = (name) => `http://${window.location.hostname}:${listenPort.value}/api/webhook/post/${name}`;
function normalizeEndpoint(name, e) {
return {
name,
enabled: e.enabled === true,
token: typeof e.token === 'string' ? e.token : '',
notifyPipes: Array.isArray(e.notifyPipes) ? e.notifyPipes : []
};
}
async function load() {
try {
const [settings, list] = await Promise.all([settingsApi.get('global'), webhookApi.list()]);
cfg.value = (settings && settings.data && settings.data.config) || {};
const map = (list && list.data && list.data.endpoints) || {};
endpoints.value = Object.entries(map)
.map(([name, e]) => normalizeEndpoint(name, e))
.sort((a, b) => a.name.localeCompare(b.name));
failed.value = false;
} catch (e) {
failed.value = true;
if (e.status) toast.error('Failed to load WebHooks: ' + e.message);
} finally {
loading.value = false;
}
}
async function saveEndpoint(name, fields, okMsg) {
saving.add(name);
try {
await webhookApi.modify({ name, ...fields });
if (okMsg) toast.success(okMsg);
return true;
} catch (e) {
toast.error('Save failed: ' + e.message);
return false;
} finally {
saving.delete(name);
}
}
async function toggleEnabled(row, value) {
const prev = row.enabled;
row.enabled = value;
if (!(await saveEndpoint(row.name, { enabled: value }))) {
row.enabled = prev;
}
}
function openAdd() {
editor.mode = 'add';
editor.name = '';
editor.token = generateToken();
editor.pipes = [];
editor.open = true;
}
function openEdit(row) {
editor.mode = 'edit';
editor.name = row.name;
editor.token = row.token;
editor.pipes = [...row.notifyPipes];
editor.open = true;
}
function togglePipe(key) {
const at = editor.pipes.indexOf(key);
if (at === -1) editor.pipes.push(key);
else editor.pipes.splice(at, 1);
}
// A 30-character hex token, so a new endpoint never starts out with a guessable
// shared secret.
function generateToken() {
const bytes = new Uint8Array(15);
crypto.getRandomValues(bytes);
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}
async function confirmEditor() {
const name = editor.name.trim();
if (!name) return toast.warn('Enter a name');
if (name.includes('/')) return toast.warn('The name cannot contain "/"');
// The backend refuses requests to an endpoint that has no token, so an
// empty one would only ever answer 500.
if (!editor.token) return toast.warn('Enter or generate a token');
const body = { name, token: editor.token, notifyPipes: [...editor.pipes] };
try {
if (editor.mode === 'add') {
// A new endpoint starts enabled; the switch in the list turns it off.
await webhookApi.add({ ...body, enabled: true });
toast.success('Endpoint added');
} else {
// enabled is deliberately left out: the list switch owns it, and a
// value read when the editor opened could undo a toggle made since.
await webhookApi.modify(body);
toast.success('Endpoint updated');
}
editor.open = false;
await load();
} catch (e) {
toast.error('Save failed: ' + e.message);
}
}
function askRemove(row) {
removing.name = row.name;
removing.open = true;
}
async function confirmRemove() {
try {
await webhookApi.remove(removing.name);
toast.success('Endpoint removed');
removing.open = false;
await load();
} catch (e) {
toast.error('Remove failed: ' + e.message);
}
}
function copy(value, okMsg) {
if (!navigator.clipboard) return toast.warn('Clipboard unavailable — copy it manually');
navigator.clipboard.writeText(value).then(() => toast.success(okMsg), () => {});
}
onMounted(load);
</script>
<template>
<section class="page">
<header class="page-head">
<div>
<p class="eyebrow">Integrations</p>
<h1>WebHooks</h1>
<p class="lead">
Let external applications push alerts through this program and relay them to the notification channels.
Where this program posts its own alerts is configured on the Settings page.
</p>
</div>
<div class="head-actions">
<button class="btn btn-ghost" @click="load">
<i class="fas fa-rotate" :class="{ 'fa-spin': loading }" /> Reload
</button>
</div>
</header>
<div v-if="failed" class="card empty">
<i class="fas fa-plug-circle-xmark e-icon" />
<p>Failed to load WebHook settings</p>
<button class="btn btn-primary" @click="load">Retry</button>
</div>
<div v-else-if="loading" class="card empty"><span class="spinner" /></div>
<template v-else>
<ConfigSection :section="apiSection" :config="cfg" @saved="load" />
<div class="card">
<div class="card-head">
<div>
<h3>Endpoints</h3>
<p class="hint">One endpoint per external application. Each carries its own token and relays to its own channels.</p>
</div>
<button class="btn btn-primary btn-sm" @click="openAdd">
<i class="fas fa-plus" /> Add endpoint
</button>
</div>
<div class="card-body">
<div v-if="endpoints.length === 0" class="empty" style="padding:28px">
No endpoints yet — add one to get an URL to post to
</div>
<div v-else class="opt-list">
<div v-for="e in endpoints" :key="e.name" class="ep-row">
<div class="ep-main">
<div class="ep-title">
<span class="id mono">{{ e.name }}</span>
<span class="badge" :class="e.enabled ? 'badge-online' : 'badge-offline'">
<span class="dot" />{{ e.enabled ? 'Enabled' : 'Disabled' }}
</span>
</div>
<div class="ep-line">
<span class="method mono">POST</span>
<span class="url mono">{{ endpointURL(e.name) }}</span>
<button class="icon-btn" title="Copy URL" @click="copy(endpointURL(e.name), 'Endpoint URL copied')">
<i class="fas fa-link" />
</button>
</div>
<div class="ep-line">
<span class="lbl">Token</span>
<span class="url mono">{{ revealed.has(e.name) ? e.token : '••••••••••••' }}</span>
<button
class="icon-btn"
:title="revealed.has(e.name) ? 'Hide token' : 'Show token'"
@click="revealed.has(e.name) ? revealed.delete(e.name) : revealed.add(e.name)"
>
<i class="fas" :class="revealed.has(e.name) ? 'fa-eye-slash' : 'fa-eye'" />
</button>
<button class="icon-btn" title="Copy token" @click="copy(e.token, 'Token copied')">
<i class="fas fa-copy" />
</button>
</div>
<div class="ep-channels">
<span v-if="e.notifyPipes.length === 0" class="badge badge-danger">
<span class="dot" />No channels
</span>
<span v-for="p in e.notifyPipes" :key="p" class="badge badge-accent">{{ channelLabel(p) }}</span>
</div>
</div>
<div class="ep-actions">
<Toggle
:model-value="e.enabled"
:disabled="saving.has(e.name)"
@update:model-value="toggleEnabled(e, $event)"
/>
<button class="icon-btn" title="Edit" @click="openEdit(e)"><i class="fas fa-pen" /></button>
<button class="icon-btn danger" title="Remove" @click="askRemove(e)"><i class="fas fa-trash" /></button>
</div>
</div>
</div>
</div>
</div>
</template>
<Modal
:open="editor.open"
:title="editor.mode === 'add' ? 'Add endpoint' : 'Edit endpoint'"
@close="editor.open = false"
>
<div class="form-grid">
<div class="field span-2">
<label>Name</label>
<input
v-model="editor.name"
class="input mono"
:disabled="editor.mode === 'edit'"
placeholder="example"
spellcheck="false"
@keydown.enter="confirmEditor"
/>
<p class="help">
Posted to <span class="mono">/api/webhook/post/&lt;name&gt;</span>. The name cannot be changed afterwards.
</p>
<p v-if="editor.mode === 'add'" class="help">
The endpoint starts enabled — use the switch in the list to disable it.
</p>
</div>
<div class="field span-2">
<label>Token</label>
<div class="token-row">
<input v-model="editor.token" class="input mono" spellcheck="false" autocomplete="off" />
<button class="btn btn-ghost btn-sm" @click="editor.token = generateToken()">
<i class="fas fa-dice" /> Generate
</button>
</div>
<p class="help">The caller sends this in the request body. An endpoint without a token rejects every request.</p>
</div>
<div class="field span-2">
<label>Relay to</label>
<div class="pipe-picker">
<button
v-for="c in CHANNELS"
:key="c.key"
type="button"
class="pipe"
:class="{ on: editor.pipes.includes(c.key) }"
@click="togglePipe(c.key)"
>
<i class="fas" :class="editor.pipes.includes(c.key) ? 'fa-square-check' : 'fa-square'" />
{{ c.label }}
</button>
</div>
<p class="help">
The alert is relayed to every channel selected here; a channel that is disabled is skipped.
The WebHook channel's own destination is configured on the Settings page.
</p>
</div>
</div>
<template #foot>
<button class="btn btn-ghost" @click="editor.open = false">Cancel</button>
<button class="btn btn-primary" @click="confirmEditor">
{{ editor.mode === 'add' ? 'Add' : 'Save' }}
</button>
</template>
</Modal>
<Modal :open="removing.open" title="Remove endpoint" @close="removing.open = false">
<p style="line-height:1.6">
Remove <strong class="mono">{{ removing.name }}</strong>? Requests to its URL will stop being accepted.
</p>
<template #foot>
<button class="btn btn-ghost" @click="removing.open = false">Cancel</button>
<button class="btn btn-danger" @click="confirmRemove">Remove</button>
</template>
</Modal>
</section>
</template>
<style scoped>
.ep-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 14px;
border-bottom: 1px solid var(--line);
}
.ep-row:last-child {
border-bottom: 0;
}
.ep-main {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.ep-title {
display: flex;
align-items: center;
gap: 10px;
}
.ep-title .id {
font-family: var(--font-mono);
font-size: 14px;
font-weight: 600;
}
.ep-line {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.ep-line .lbl {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-3);
font-weight: 600;
}
.ep-line .url {
font-family: var(--font-mono);
font-size: 12.5px;
color: var(--text-2);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.method {
font-size: 10.5px;
font-weight: 700;
letter-spacing: 0.06em;
padding: 1px 6px;
border-radius: var(--r-s);
background: var(--accent-soft);
color: var(--accent);
}
.ep-channels {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
margin-top: 2px;
}
.ep-actions {
display: flex;
align-items: center;
gap: 10px;
flex-shrink: 0;
}
.token-row {
display: flex;
align-items: center;
gap: 8px;
}
.token-row .input {
flex: 1;
min-width: 0;
}
.pipe-picker {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.pipe {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 6px 11px;
border: 1px solid var(--line-strong);
border-radius: var(--r-pill);
background: var(--surface-2);
color: var(--text-3);
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: border-color 0.14s ease, color 0.14s ease, background 0.14s ease;
}
.pipe:hover {
color: var(--text);
}
.pipe.on {
border-color: var(--accent);
background: var(--accent-soft);
color: var(--accent);
font-weight: 600;
}
</style>